是什么" ?? "运营商在C#中? [英] what is "?? "operator in c#?
问题描述
可能重复:结果
的什么是“ ??”的运营商?
块引用>
什么的?运营商的表达式执行?
公开元数据的NameValueCollection
{
{返回的元数据? (元数据=新的NameValueCollection()); }
}
解决方案这就是所谓的空-coalescing运营商,它如下,假设作用
A
是一个可空int和b
是一个正常的INTb = 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 andb
is a normal intb = 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屋!