我目前正在为我们公司的一个项目启用可空选项,但我不确定如何处理以下情况。
public class MyCollection<T>
{
private T[] myArray;
public T this[int i]
{
get => myArray[i];
set => myArray[i] = value;
}
}
如果 T 是引用类型,我希望 null 是一个有效值。但是在值类型的情况下,我不想要 Nullable<T>
要参与其中,请保持类型不变。
我尝试使用注释,但最后如果value
在 setter 中可以为 null,我不得不声明 myArray
作为T?[]
.
public class MyCollection<T>
{
private T[];
[AllowNull]
public T this[int i]
{
[return: MaybeNull]
get => myArray[i];
set => myArray[i] = value; // Possibly null
}
}
所以我想我的问题是:
- 如果我做
myArray
一个T?[]
, 编译器会强制使用Nullable<T>
对于值类型? - 如果是这样,有没有办法做我想做的事?
最佳答案
在 C# 9 中,您可以申请 ?
到“不受约束的通用类型”,它不会产生 Nullable<T>
如果T
是 struct
.
所以你的例子变成了:
public class MyCollection<T>
{
private T?[] myArray;
public T? this[int i]
{
get => myArray[i];
set => myArray[i] = value;
}
}
属性也可以,但不太优雅。
关于c# - 可空启用与 T 的集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67825471/