相关疑难解决方法(0)

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

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

int? val = null;
Run Code Online (Sandbox Code Playgroud)

但是自定义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 …
Run Code Online (Sandbox Code Playgroud)

.net c#

4
推荐指数
1
解决办法
1198
查看次数

标签 统计

.net ×1

c# ×1