如何检查泛型类型参数是否可以为null



可能重复:
确定通用参数是否为可为null类型的

我正在尝试确定一个类型参数是否可以为null。

    public T Get<T>(int index)
    {
        var none=default(T);
        var t = typeof(T);
        BaseVariable v = this[index].Var;
        if (T is Nullable) //compiler error
        {
            if (v == ... )
            {
                return none;
            }
        }
        //....
    }

我该怎么做?我试过做t == typeof(Nullable),但结果总是错误的。

我希望foo.Get<bool?>(1)有时为null。

您可以使用Nullable.GetUnderlyingType:

var t = typeof(T);
// ...
if (Nullable.GetUnderlyingType(t) != null)
{
    // T is a Nullable<>
}

最新更新