如何检查泛型类型参数是否可为空?

Ear*_*rlz 19 .net c# generics nullable

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

我正在尝试确定类型参数是否为Nullable.

    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;
            }
        }
        //....
    }
Run Code Online (Sandbox Code Playgroud)

我该怎么做呢?我尝试过,t == typeof(Nullable)但总是导致错误.

我想要发生的是foo.Get<bool?>(1)有时无效.

Luk*_*keH 41

你可以使用Nullable.GetUnderlyingType:

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