Why C # null can implicitly convert to System.Nullable <T>, but cannot Nullable <T> self-define

Why nullcan implicitly convert to System.Nullable<T>as follows:

int? val = null;

but self-determining Nullable<T>(modified from .net information source) cannot assign nullif there is any kind of compiler magic? Can someone tell me a more internal interpretation?

[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;
    }
}

test code below compilation error

Nullable<int> x = null; //ERROR Cannot convert null to 'Nullable<int>' because it is a non-nullable value type
+4
source share
1 answer

Section 6.1.5 of the C # 5.0 specification:

6.1.5
. (§ 4.1.1) .

, , , . Nullable<T> NULL, #. - , , Nullable<T> ( 4.1.10), "" #.

+5

All Articles