?.操作符

84 阅读1分钟

问题: 是否有办法缩短下面的code

if (obj != null)
    obj.SomeMethod();

答案:有

obj?.SomeMethod();

?.是一个null的传播算子,值为null时会短路掉SomeMethod()

The ?. is the null-propagating operator, and will cause the .Invoke() to be short-circuited when the operand is null.

?.只被access一次,所以不存在检查和调用之间值发生变化这种情况

The operand is only accessed once, so there is no risk of the "value changes between check and invoke" problem.