本文介绍了是什么" ?? "运营商在C#中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

What does the "??" operator perform in an expression ?

public NameValueCollection Metadata
{
    get { return metadata ?? (metadata = new NameValueCollection()); }
}
解决方案

This is known as null-coalescing operator and it acts as following, assume a is a nullable int and b is a normal int

b = a ?? 1;

is equal to

b = (a != null ? (int)a : 1);

which is equal to

if(a != null)
    b = (int)a;
else
    b = 1;

Therefore

public NameValueCollection Metadata
{
    get { return metadata ?? (metadata = new NameValueCollection()); }
}

expanded should look like something like this

public NameValueCollection Metadata
{
    get
    {
        if(metadata == null)
            return (metadata = new NameValueCollection());
        else
            return metadata;
    }
}

which is some kind of a one liner singleton pattern, because the getter returns metadata (an initialized NameValueCollection object) every time its requested, expect the very first time which it's null at that point, so it initializes it and then returns it. This is off topic but note that this approach to singleton pattern is not thread-safe.

这篇关于是什么" ?? "运营商在C#中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 18:43