C# --- Null Operator

C# --- Null Operator

  • Null-Coalescing Operator ??
  • Null-Coalescing Assignment Operator ??=
  • Null-Conditional Operator ?.

  • C#提供了三种操作符用来更方便的处理 null value

Null-Coalescing Operator ??

  • ?? 操作符叫做null-coalescing operator.
  • 表示如果左侧的操作数非空, 则返回它; 否则, 返回另一个值
string s1 = null;
//如果s1不是null则返回s1,如果s1是null则返回 "nothing"
string s2 = s1 ?? "nothing"; // s2 evaluates to "nothing"

Null-Coalescing Assignment Operator ??=

  • ??= 操作符是null-coalescing assignment operator.
  • 表示如果左侧的操作数是null, 则将右边的操作数赋值给左边
myVariable ??= someDefault;
//等于
if (myVariable == null) myVariable = someDefault;

Null-Conditional Operator ?.

  • ?. operator表示如果左侧的操作数为null, 则表达式的值为null, 而不会抛出NullReferenceException
System.Text.StringBuilder sb = null;
// No error; s instead evaluates to null
string s = sb?.ToString(); 
//等于 string s = (sb == null ? null : sb.ToString());
string foo = null;
char? c = foo?[1]; 
// c is null, char? 表示让char可以为null的意思
//具体见 Nullale Value Types
System.Text.StringBuilder sb = null;
// s evaluates to null without error
string s = sb?.ToString().ToUpper(); 
//If someObject is null, this becomes a “no-operation” 
//rather than throwing a NullReferenceException.
someObject?.SomeVoidMethod();
//可以混合使用
System.Text.StringBuilder sb = null;
string s = sb?.ToString() ?? "nothing";

你可能感兴趣的:(#,C#,---,语法糖,c#)