可空类型

可空类型

  可空类型可以表示基础类型的所有值,另外还可以表示 null 值。可空类型可通过下面两种方式中的一种声明:

    System.Nullable<T> variable

  - 或 -

    T? variable

  T 是可空类型的基础类型。T 可以是包括 struct 在内的任何值类型;但不能是引用类型。

  

  可空类型的每个实例都具有两个公共的只读属性:

  • HasValue

    HasValue 属于 bool 类型。当变量包含非空值时,它被设置为 true

  • Value

    Value 的类型与基础类型相同。如果 HasValue 为 true,则说明 Value 包含有意义的值。如果 HasValue 为 false,则访问 Value 将引发 InvalidOperationException

int? x = 10;
if (x.HasValue){
}

int? y = 10;
if (y != null){
}

  ?? 运算符定义在将可空类型分配给非可空类型时返回的默认值。

int? c = null;

// d = c, unless c is null, in which case d = -1.
int d = c ?? -1;


int? e = null;
int? f = null;

// g = e or f, unless e and f are both null, in which case g = -1.
int g = e ?? f ?? -1;

参考:

1、https://msdn.microsoft.com/zh-cn/library/1t3y8s4s(v=vs.80).aspx

原文地址:https://www.cnblogs.com/tekkaman/p/6135423.html