可空类型(Nullable)及其引出的关于explicit、implicit的使用

问题一:Nullable<T>可赋值为nullspa

先看两行C#代码调试

            int? i1 = null;
            int? i2 = new int?();        

int? 即Nullable<int>,就像int之于Int32;code

Nullable<T>是很是特殊结构类型,它可赋值为null(因此此前我还觉得是引用类型),其本质是等同于new;对象

经过调试可发现上述两个值均为null,可是事实上咱们却能够调用他们的一些属性方法好比“HasValue”,因而可知“=null“只是障眼法罢了;blog

此时若是调用他们的”Value“属性将引起”InvalidOperationException“异常,注意不是空引用异常,异常信息为”其余信息: 可为空的对象必须具备一个值。”;ci

建议对于此类型的取值使用“GetValueOrDefault”方法来获取,而不是判断HasValue后去Value值;get

其次建议不进行” == null “的逻辑判断,应使用HasValue属性。string

 

问题二:Nullable<T> 可赋值为 T类型it

 仍然看两行C#代码io

            int? iNull = 2;
            int i = (int)iNull;

很是常见的代码,可是每行代码都包含了类型,“int?”与int之间的隐式转换与显示转换,而支持可空类型转换的就是Nullable<T>提供了两个方法:

        public static explicit operator T(Nullable<T> value);
        public static implicit operator Nullable<T>(T value);

operator是运算符重载,于是这俩货也能够当作是对“=”的运算符重载,explicit支持了显示转换,implicit支持了隐式转换,使用以下:

    class UserInfo
    {
        public int ID { get; set; }

        public string Name { get; set; }

        public static explicit operator UserInfo(int id)
        {
            Console.WriteLine("获取用户ID为【{0}】的User对象", id);
            return new UserInfo { ID = id };
        }

        public static implicit operator UserInfo(string name)
        {
            Console.WriteLine("获取用户名为【{0}】的User对象", name);
            return new UserInfo { Name = name };
        }
    }

调用:

            UserInfo user1 = (UserInfo)2;

            UserInfo user2 = "bajie";
相关文章
相关标签/搜索