Nullable 类型如何在幕后工作?

我很想知道Nullable类型如何在幕后工作。 它是否正在创建一个新对象(对象可以赋值为null),其值可能为null?

在我们使用Nullable 的例子中,当你为它赋值空值时,它们是从对象到int的某种隐式转换,反之亦然?

另外我知道如何手动创建它,使用Nullable类型是否有好处,而不是自己创建它?

可空类型是由两个字段组成的结构: boolT 当值为null时,bool为false,T具有默认值。 当值不为null时,bool为true。

与自己实现function相比,使用Nullable有两个主要好处。 有语言支持,如ChaosPandion的答案中更详细的描述,并且拳击(转换为object )将自动删除可空的“包装器”,留下空引用或普通T对象.z

以下是针对Nullable运行.Net Reflector的(整理)代码…

 [Serializable, StructLayout(LayoutKind.Sequential), TypeDependency("System.Collections.Generic.NullableComparer`1"), TypeDependency("System.Collections.Generic.NullableEqualityComparer`1")] public struct Nullable where T: struct { private bool hasValue; internal T value; public Nullable(T value) { this.value = value; this.hasValue = true; } public bool HasValue { get { return this.hasValue; } } public T Value { get { if (!this.HasValue) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_NoValue); } return this.value; } } public T GetValueOrDefault() { return this.value; } public T GetValueOrDefault(T defaultValue) { if (!this.HasValue) { return defaultValue; } return this.value; } public override bool Equals(object other) { if (!this.HasValue) { return (other == null); } if (other == null) { return false; } return this.value.Equals(other); } public override int GetHashCode() { if (!this.HasValue) { return 0; } return this.value.GetHashCode(); } public override string ToString() { if (!this.HasValue) { return ""; } return this.value.ToString(); } public static implicit operator Nullable(T value) { return new Nullable(value); } public static explicit operator T(Nullable value) { return value.Value; } } 

它实际上非常简单。 编译器为您提供了语法。

 // this int? x = null; // Transformed to this int? x = new Nullable() // this if (x == null) return; // Transformed to this if (!x.HasValue) return; // this if (x == 2) return; // Transformed to this if (x.GetValueOrDefault() == 2 && x.HasValue) return; 

Nullable实现为一个结构,如果HasValuefalse ,则覆盖Equals()以表现为null 。 从TT?的隐式转换T? ,以及如果!HasValue抛出的另一个方向的显式转换。