Nullable <T>类型如何在幕后工作?

Edw*_*ard 13 .net c#

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

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

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

Ran*_*832 13

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

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

  • 具体是什么方面?http://msdn.microsoft.com/en-us/library/ms228597.aspx解释了拳击的事情. (3认同)

bar*_*oyd 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;
}
}
Run Code Online (Sandbox Code Playgroud)

  • hasValue默认为False,仅在构造函数中设置为True (2认同)

Cha*_*ion 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;
Run Code Online (Sandbox Code Playgroud)