这是空值合并运算符,它在C# 2中被引入。
表达式a ?? b
的结果是如果a
不是null,则为a
,否则为b
。除非需要,否则不会评估b
。
两个好处:
The overall type of the expression is that of the second operand, which is important when you're using nullable value types:
int? maybe = ...;
int definitely = maybe ?? 10;
(Note that you can't use a non-nullable value type as the first operand - it would be pointless.)
The associativity rules mean you can chain this really easily. For example:
string address = shippingAddress ?? billingAddress ?? contactAddress;
a
一次之外,它什么都没有。 - Jon Skeet它被称为“null合并运算符”,其工作原理大致如下:
不要这样做:
int? number = null;
int result = number == null ? 0 : number;
现在你可以这样做:
int result = number ?? 0;
call instance !0 valuetype [mscorlib]System.Nullable
1<int32>::GetValueOrDefault()`)。 - Aidiakapi这是 coalesce 运算符。它本质上是以下内容的速记:
x ?? new Student();
x != null ? x : new Student();
操作符的MSDN文档
这是一个快捷方式:
Text = (category == null ? "Home" : category);
这是新的 Null Coalesce 操作符。
如果左侧操作数不为 null,则 ?? 操作符返回左侧操作数,否则返回右侧操作数。
您可以在此处阅读更多信息: http://msdn.microsoft.com/en-us/library/ms173224(VS.80).aspx
这是一个合并运算符,如果第一个值为空,它将返回另一个值。
string value1 = null;
string value2 = "other";
string value3 = value1 ?? value2; // assigns "other" to value 3
它会检查类别是否为空 - 当这种情况发生时,空值将被替换为“主页”。
我最喜欢使用空值合并运算符的方法之一是避免在代码中使用if语句(我认为if语句往往很丑陋,只会让事情变得混乱)。例如,考虑一个典型的场景,如果可用,则从缓存中加载某些内容,否则从数据库中加载并填充缓存。
private SomeData GetData() {
var data = HttpRuntime.Cache.Get("key") as SomeData;
if (data == null) {
data = DAL.GetData(some parameters...);
HttpRuntime.Cache.Add("key", data, ....);
}
return data;
}
private SomeData GetDataAndCache() {
var data = DAL.GetData(some parameters...);
HttpRuntime.Cache.Add("key", data, ....);
return data;
}
private SomeData GetData() {
var data = HttpRuntime.Cache.Get("key") as SomeData;
return data ?? GetDataAndCache();
}
在我看来,它更贴近SRP原则,也更加简洁易读。每个函数都只执行一个明确可识别的功能。