我正在尝试做这样的事情:
public class MySuperCoolClass<T>
{
public T? myMaybeNullField {get; set;}
}
这可能吗?
这给了我错误:
error CS0453: The type
T' must be a non-nullable value type in order to use it as type parameter
T' in the generic type or method System.Nullable'.
谢谢
最佳答案
添加where T : struct
自 Nullable<T>
以来消除错误的通用约束只接受 struct
.
public class MySuperCoolClass<T> where T : struct
{
public T? myMaybeNullField { get; set; }
}
Nullable<T>
定义如下
public struct Nullable<T> where T : struct
所以你也被迫这样做,只是为了阻止你这样做MySuperCoolClass<object>
这使得 object?
这是无效的。
关于c# - 泛型类中的可空泛型字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20353742/