如何确保泛型参数不可空?
How to ensure a generic parameter is not Nullable?
我正在尝试制作一个 class GameOption
来保存三个(实际上是四个)值:
选项名称为字符串
选项为T
默认值为 Nullable< T >
这看起来像我的 class:
public class GameOption<T> {
private T v;
private string n;
private T? def;
public string Name { get => this.n; }
public T Value { get => this.v; }
public GameOption(T o, string name, T? def) {
this.n = name;
this.v = o;
}
public void ChangeValue(T o) {
this.v = o;
}
}
但是有个问题。正如 VS 所说,T 不能为空:
The type T must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method Nullable
如何确保 T 不可为空?
有没有像class X<@NotNull T>
之类的东西?
为确保类型 T
不可空,将其约束为 struct
:
public class GameOption<T> where T : struct { }
我正在尝试制作一个 class GameOption
来保存三个(实际上是四个)值:
选项名称为字符串
选项为T
默认值为 Nullable< T >
这看起来像我的 class:
public class GameOption<T> {
private T v;
private string n;
private T? def;
public string Name { get => this.n; }
public T Value { get => this.v; }
public GameOption(T o, string name, T? def) {
this.n = name;
this.v = o;
}
public void ChangeValue(T o) {
this.v = o;
}
}
但是有个问题。正如 VS 所说,T 不能为空:
The type T must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method Nullable
如何确保 T 不可为空?
有没有像class X<@NotNull T>
之类的东西?
为确保类型 T
不可空,将其约束为 struct
:
public class GameOption<T> where T : struct { }