shuse

导航

 
总结了下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,但是Customernull,此时Customer?.FirstName会返回null而不是抛出个NullReferenceException

再看看下面的代码,你就会知道怎么用了:

  1. //如果不是客户或命令无效,这将抛出一个像往常一样空引用异常
  2. int orderNumber = Customer.Order.OrderNumber;    
  3. //这将无法编译,因为它需要一个空的返回类型     
  4. int orderNumber = Customer.Order?.OrderNumber;    
  5. //这将返回null,如果客户是空或者如果命令是空     
  6. int? orderNumber = Customer?.Order?.OrderNumber;    
  7. if (orderNumber.HasValue)    
  8. //... 用它做一些事情   
  9. //而不是必须做   
  10. if ((Customer != null) && (Customer.Order != null)) 
  11. int a = Customer.Order.OrderNumber 
posted on 2011-12-23 02:32  shuse  阅读(267)  评论(0)    收藏  举报