class Test<T>
{
T? obj;
}
错误:
The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'System.Nullable'
我需要保留对类型 T 的可能为空的引用,但 T 可以是值类型或引用类型,而且您不能拥有
Nullable<T>
如果 T 是引用类型。有什么解决办法吗?
最佳答案
只有值类型可以为空(引用类型本质上已经可以为空)。所以你可以应用与 Nullable<T>
相同的通用约束类(class):
class Test<T> where T: struct
{
T? obj;
}
这当然是相同的:
class Test<T> where T: struct
{
Nullable<T> obj;
}
并说明泛型参数必须满足相同的约束。
关于.net - 如果 T 是类型 arg,如何使用 Nullable<T>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7705741/