可空值类型
[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; } }
学习永不止境,技术成就梦想。