是什么" ?? "运营商在C#中? [英] what is "?? "operator in c#?

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

问题描述


可能重复:结果
什么是“ ??”的运营商?






什么的?运营商的表达式执行?



 公开元数据的NameValueCollection 
{
{返回的元数据? (元数据=新的NameValueCollection()); }
}


解决方案

这就是所谓的空-coalescing运营商,它如下,假设作用 A 是一个可空int和 b 是一个正常的INT

  b = A? 1; 



等于

  b =(!?一个= NULL(INT)答:1); 



等于

 如果(一个!= NULL)$ b $ = BB(INT)一个; 
,否则
B = 1;



因此

 公开元数据的NameValueCollection 
{
{返回的元数据? (元数据=新的NameValueCollection()); }
}



拓展看起来应该像这样

 公开元数据的NameValueCollection 
{
得到
{
如果(元数据== NULL)
返回(元数据=新的NameValueCollection());
,否则
返回元数据;
}
}



这是某种单行Singleton模式,因为吸气回报的元数据(初始化的对象的NameValueCollection),其每一个要求的时间,想到的第一次,它是空在这一点上,所以它初始化,然后返回。这是题外话,但请注意,这种方法singleton模式是不是线程安全的。


Possible Duplicate:
What is the “??” operator for?

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#中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆