sap*_*ket 2 c# generics nullable
如果我宣布以下内容:
public T[] GetFoo<T>(int length)
{
return new T[length];
}
Run Code Online (Sandbox Code Playgroud)
在客户端代码中我调用上面这样:
int[] foo = GetFoo<int>(3);
Run Code Online (Sandbox Code Playgroud)
然后foo[]
将像这样初始化:
foo[0]=0;
foo[1]=0;
foo[2]=0;
Run Code Online (Sandbox Code Playgroud)
有没有办法可以让它像这样初始化?
foo[0]=null;
foo[1]=null;
foo[2]=null;
Run Code Online (Sandbox Code Playgroud)
我问,因为'0'有特殊含义,我想用'null'代替表示数组元素尚未设置.请注意,我使用的是泛型,有时我不会使用int - 例如,有时我可能会使用引用类型.
int
是一个无法设置的值类型null
.如果要允许空值,则必须将其Nullable<int>
用作类型参数,或者更加简洁int?
.
int?[] foo = GetFoo<int?>(3);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
227 次 |
最近记录: |