A nullable type is a value type that can be null.
(1)与基础结构相比,值类型的惟一开销是一个布尔成员,该成员告诉值类型是否为null
(2)int可以直接赋值给int?
int a=1;
int? b=a;
(3)int?不可以直接赋值给int,需要强制转换
int a = (int)b;
1)Of course, the cast generates an exception in a case where b is null.
当b为null时,赋值给a会报错
2)A better way to deal with that is to use the HasValue and Value properties of nullable types.
int a = b.HasValue ? b.Value : -1;
In a case where 'b' is null, HasValue returns false, and here −1 is supplied to the variable 'a'.
3)Using the coalescing operator ??, there’s a shorter syntax possible with nullable types.
In a case where 'b' is null, −1 is set with the variable 'a'; otherwise you take the value of b:
int a = b ?? -1;
可空类型的另一种表示方式:struct Nullable<T> 可空结构体
Nullable<int> c; (泛型T为int类型)
int? d;
网友评论