开发者

How to check if a generic type parameter is nullable? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Determine if a generic param is a Nullable type

I'm trying to determine if a type parameter is Nullable.

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

How do I do this? I've tried doing t == typeof(Nullable) but that always resulted in false.

What I want to happen is for foo.Get<bool?>(1) to null at times.


You can use Nullable.GetUnderlyingType:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜