【问题标题】:How to check if a generic type parameter is nullable? [duplicate]如何检查泛型类型参数是否可以为空? [复制]
【发布时间】:2011-06-22 00:58:11
【问题描述】:

可能重复:
Determine if a generic param is a Nullable type

我正在尝试确定类型参数是否为 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;
            }
        }
        //....
    }

我该怎么做?我试过做t == typeof(Nullable) 但这总是导致错误。

我希望 foo.Get&lt;bool?&gt;(1) 有时为空。

【问题讨论】:

标签: c# .net generics nullable


【解决方案1】:

你可以使用Nullable.GetUnderlyingType:

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

【讨论】:

  • 这在我使用 C#8.0 的 .NET Core 3.1 版本中不起作用
  • 在 net5.0/c#9 中工作,fwiw
猜你喜欢
  • 2022-09-23
  • 2011-11-12
  • 1970-01-01
  • 1970-01-01
  • 2014-01-15
  • 1970-01-01
  • 2023-03-29
  • 1970-01-01
  • 2013-08-16
相关资源
最近更新 更多