Nullable<T> 内部实现了显示和隐式转换
显示转换:
public static explicit operator T(T? value) { return value.Value; }
Nullable<int> nullable = new Nullable<int>(10);
int x = (int)nullable;
隐式转换:
public static implicit operator T?(T value) { return new T?(value); }
Nullable<int> i = 100;
装箱拆箱:
Nullable<int> nullable = 100; object boxed = nullable;//有值的可空类型装箱 Console.WriteLine(boxed.GetType());//System.Int32 int normal = (int)boxed;//有值的可空类型拆箱成非可空类型 Console.WriteLine(normal); nullable = (Nullable<int>)boxed;//有值的可空类型拆箱成可空类型 Console.WriteLine(nullable); nullable = new Nullable<int>(); boxed = nullable;//没有值的可空类型装箱 Console.WriteLine(boxed == null);//True nullable = (Nullable<int>)boxed;//没有值的可空类型拆箱成可空类型 Console.WriteLine(nullable.HasValue);//False