深入理解 c# 第四章 使用Nullable<T>的各个成员

    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(): 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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值