我很想知道Nullable类型如何在幕后工作。它是否正在创建一个新对象(对象可以赋值为null),其值可能为null?
在我们使用Nullable< int>的示例中,当你为它赋值空值时,它们是从对象到int的某种隐式转换,反之亦然吗?
我也知道如何手动创建它,使用Nullable类型是否有好处,而不是自己创建?
答案 0 :(得分:13)
可空类型是由两个字段组成的结构:bool
和T
。当值为null时,bool为false,T具有默认值。当值不为null时,bool为真。
与自己实现功能相比,使用Nullable
有两个主要好处。有语言支持,如ChaosPandion的答案中更详细的描述,而且拳击(转换为object
)将自动删除可空的“包装器”,留下空引用或普通T对象。 ž
答案 1 :(得分:11)
以下是针对Nullable运行.Net Reflector的(整理)代码...
[Serializable, StructLayout(LayoutKind.Sequential), TypeDependency("System.Collections.Generic.NullableComparer`1"), TypeDependency("System.Collections.Generic.NullableEqualityComparer`1")]
public struct Nullable<T> 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>(T value)
{
return new Nullable<T>(value);
}
public static explicit operator T(Nullable<T> value)
{
return value.Value;
}
}
答案 2 :(得分:9)
实际上非常简单。编译器为您提供了语法。
// this
int? x = null;
// Transformed to this
int? x = new Nullable<int>()
// 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;
答案 3 :(得分:1)
Nullable<T>
被实现为一个结构,如果Equals()
为null
,则覆盖HasValue
以表现为false
。存在从T
到T?
的隐式转换,以及在!HasValue
时抛出的另一个方向的显式转换。