C# 如何检查泛型类型参数是否可为null?
可能重复:C# 如何检查泛型类型参数是否可为null?,c#,.net,generics,nullable,C#,.net,Generics,Nullable,可能重复: 我试图确定类型参数是否可以为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 == ... )
我试图确定类型参数是否可以为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;
}
}
//....
}
publictget(int索引)
{
var none=默认值(T);
var t=类型(t);
BaseVariable v=此[index].Var;
if(T可为null)//编译器错误
{
如果(v==…)
{
不返回任何值;
}
}
//....
}
我该怎么做?我尝试过做t==typeof(Nullable)
,但结果总是错误的
我想让foo.Get(1)
有时为空。您可以使用:
var t=typeof(t);
// ...
if(可为null.GetUnderlineType(t)!=null)
{
//T是可为空的
}
这是VB中的dup@Nix,所以可能是边界而不是dup。我们将看到解决方案是在C#和VBA中实现的,这在我的.NET Core 3.1版本和C#8.0中不起作用
var t = typeof(T);
// ...
if (Nullable.GetUnderlyingType(t) != null)
{
// T is a Nullable<>
}