C# NULL值条件运算符 ?.

Null值条件运算符属于C#6.0的语法糖

使用方法:变量名?.属性

下列Person为使用到的类

1     public class Person
2     {
3         public string Name { get; set; }
4 
5         public int Age { get; set; }
6 
7         public int? Height { get; set; }
8     }

如果使用下列调用方式,则会引起NullReferenceException异常

为了容错,我们一般会在代码里写这样的判断

1 Person p = null;
2 if (p!=null)
3 {
4      string pName = p.Name;
5 }

在C#6.0以后推出了Null值条件运算符,我们可以简化成这样的写法

1 Person p = null;
2 string pName = p?.Name;

 当然我们也可以使用三元运算符来做判断

1 string pName = p == null ? null : p.Name;

我在项目中经常使用到该运算符,在一些带有释放资源的finally代码块中使用会引起非常的舒适

如果项目中支持C#6.0那么最好是优先使用此方法,与if使用方式来说两者的IL代码是不同的,对该运算符的IL代码有想深入了解请参考此博客https://www.cnblogs.com/linianhui/p/csharp6_null-conditional-operators.html#auto_id_1

猜你喜欢

转载自www.cnblogs.com/c-j-s/p/10215794.html