class NullableMembers
{
static void Display(Nullable<int> x) //显示诊断结果
{
Console.WriteLine("HasValue: {0}", x.HasValue);
if (x.HasValue)
{
Console.WriteLine("Value: {0}", x.Value);
Console.WriteLine("Explicit conversion: {0}", (int)x);
}
Console.WriteLine("GetValueOrDefault(): {0}",
x.GetValueOrDefault());
Console.WriteLine("GetValueOrDefault(10): {0}",
x.GetValueOrDefault(10));
Console.WriteLine("ToString(): \"{0}\"", x.ToString());
Console.WriteLine("GetHashCode(): {0}", x.GetHashCode());
Console.WriteLine();
}
static void Main()
{
Nullable<int> x = 5;
x = new Nullable<int>(5);
Console.WriteLine("Instance with value:");
Display(x);
x = new Nullable<int>();
Console.WriteLine("Instance without value:");
Display(x);
}
}
Nullable<int> x = 5;
x = new Nullable<int>(5);
包装等于5的值
x = new Nullable<int>();
构造没有值的实例
输出
Instance with value:
HasValue: True //包装就true
Value: 5 //包装的值是5
Explicit conversion: 5 //显式变换是5
GetValueOrDefault(10): 5 //当10做参数时,得到的值是5
ToString(): "5" //变成字符串
GetHashCode(): 5 //返回的值是5
Instance without value:
HasValue: False //没包装
GetValueOrDefault(): 0 //默认值为0
GetValueOrDefault(10): 10 //有10做参数,结果为10
ToString(): "" //字符串为空
GetHashCode(): 0 //返回的值为0