本文主要是介绍C# null operators,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Null-Coalescing Operator
The ?? operator is the null-coalescing operator. It says, “If the operand to the left is non-null, give it to me; otherwise, give me another value.” For example:
string s1 = null;
string s2 = s1 ?? "nothing"; // s2 evaluates to "nothing"
If the lefthand expression is non-null, the righthand expression is never evaluated.
Null-Coalescing Assignment Operator
The ??= operator (introduced in C# 8) is the null-coalescing assignment operator. It says, “If the operand to the left is null, assign the right operand to the left operand.” Consider the following:
myVariable ??= someDefault;
This is equivalent to:
if (myVariable == null) myVariable = someDefault;
The ??= operator is particularly useful in implementing lazily calculated properties.
Null-Conditional Operator
The ?. operator is the null-conditional or “Elvis” operator (after the Elvis emoticon). It allows you to call methods and access members just like the standard dot operator except that if the operand on the left is null, the expression evaluates to null instead of throwing a NullReferenceException:
System.Text.StringBuilder sb = null;
string s = sb?.ToString(); // No error; s instead evaluates to null
The last line is equivalent to the following:
string s = (sb == null ? null : sb.ToString());
Upon encountering a null, the Elvis operator short-circuits the remainder of the expression. In the following example, s evaluates to null, even with a standard dot operator between ToString() and ToUpper():
System.Text.StringBuilder sb = null;
string s = sb?.ToString().ToUpper(); // s evaluates to null without error
这篇关于C# null operators的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!