为什么 c# null 可以隐式转换为 <T>System.Nullable,但不能自定义 Null<T>



为什么null可以像这样隐式转换为System.Nullable<T>

int? val = null;

但是自定义Nullable<T>(从.NET引用源修改)无法分配null,是否有一些编译器魔法?谁能告诉我更多的内心暗示?

[Serializable]
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 hasValue;
        }
    }
    public T Value
    {
        get
        {
            if (!HasValue)
            {
                throw new Exception();
            }
            return value;
        }
    }
    public T GetValueOrDefault()
    {
        return value;
    }
    public T GetValueOrDefault(T defaultValue)
    {
        return HasValue ? value : defaultValue;
    }
    public override bool Equals(object other)
    {
        if (!HasValue) return other == null;
        if (other == null) return false;
        return value.Equals(other);
    }
    public override int GetHashCode()
    {
        return HasValue ? value.GetHashCode() : 0;
    }
    public override string ToString()
    {
        return HasValue ? 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;
    }
}

下面的测试代码,编译错误

Nullable<int> x = null; //ERROR Cannot convert null to 'Nullable<int>' because it is a non-nullable value type

C# 5.0 规范的第 6.1.5 节:

6.1.5 空文字转换
存在从 null 文本到任何可为 null 类型的隐式转换。此转换生成给定可为空类型的空值 (§4.1.10)。

请注意,此编译器提供的隐式转换仅存在于可为 null 的类型。自定义Nullable<T>不是 C# 规范定义的可为 null 的类型。它只是您声明的一些结构,它具有内置Nullable<T>类型的许多功能(在引用的第 4.1.10 节中描述),但实际上根据 C# 中的定义,它不是"可为空的"。

最新更新