Fork me on GitHub

可空值类型

[Serializable,StructLayout(LayoutKind.Sequential)]
    public struct Nullable<T> where T : struct
    {
        //这两个字段标识状态
        private Boolean hasValue = false;//假定null
        internal T value = default(T);//假定所有位都为零

        public Nullable(T value)
        {
            this.value = value;
            hasValue = true;
        }

        public T GetValueOrDefault()
        {
            return value;
        }

        public T GetValueOrDefault(T defaultValue)
        {
            if (!hasValue) return defaultValue;
            return value;
        }

        public override bool Equals(object obj)
        {
            if (!hasValue) return obj == null;
            if (obj == null) return false;
            return value.Equals(obj);
        }

        public override int GetHashCode()
        {
            if (!hasValue) return 0;
            return value.GetHashCode();
        }

        public override string ToString()
        {
            if (!hasValue) return "";
            return value.ToString();
        }
        //隐式转换
        public static implicit operator Nullable<T>(T value)
        {
            return new Nullable<T>(value);
        }
        //显式装换
        public static explicit operator T(Nullable<T> value)
        {
            return value.value;
        }
    }

 

posted on 2017-06-22 21:41  *Hunter  阅读(154)  评论(0编辑  收藏  举报

导航

AmazingCounters.com