总结了下nullable变量类型的基本用法,希望对大家有所帮助
int? a = default(int?); // a is the null value
int? b = default(int); //b is the integer 0.
int? c = 5; // c is the integer 5.
bool aHasValue = a.HasValue; // false
bool bHasValue = b.HasValue; // true;
bool cHasValue = c.HasValue; // true
int aValue = a.Value; // throws InvalidOperationException.
int bValue = b.Value; // bValue is 0
int cValue = c.Value; // cValue is 5;
int aValueOrDefault = a.GetValueOrDefault(); // returns 0
int bValueOrDefault = b.GetValueOrDefault(); // returns 0
int cValueOrDefault = c.GetValueOrDefault(); // return 5
int aSafeValue = a ?? 42; // aSafeValue is 42.
int bSafeValue = b ?? 42; // bSafeValue is 0; nullable变量类型的变形用法-- 安全的null延迟赋值操作符
假设需要一种安全地访问一个值为null的对象的属性的表达式,表达式可能形如Object.Property.Property.Value
比如我要访问Customer?.FirstName,但是Customer是null,此时Customer?.FirstName会返回null而不是抛出个NullReferenceException
再看看下面的代码,你就会知道怎么用了:
- //如果不是客户或命令无效,这将抛出一个像往常一样空引用异常
- int orderNumber = Customer.Order.OrderNumber;
- //这将无法编译,因为它需要一个空的返回类型
- int orderNumber = Customer.Order?.OrderNumber;
- //这将返回null,如果客户是空或者如果命令是空
- int? orderNumber = Customer?.Order?.OrderNumber;
- if (orderNumber.HasValue)
- //... 用它做一些事情
- //而不是必须做
- if ((Customer != null) && (Customer.Order != null))
- int a = Customer.Order.OrderNumber
浙公网安备 33010602011771号