C# --- Null 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";
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值