相关疑难解决方法(0)

多维数组、可为 null 的引用类型和类型转换

使用 C# 8 的可空引用类型,我们可以编写(对于引用类型):

T x = ...;
T? y = x;
Run Code Online (Sandbox Code Playgroud)

但是,我无法理解多维和锯齿状数组的转换规则。

string[][] a = new string[1][];
string?[]?[] b = new string[1][];
string?[]?[]? c = new string[1][];
string?[,][] d = new string[1,2][];
string?[,][]? e = new string[1,2][];
string?[,]?[] f = new string[1,2][];   // compiler error
Run Code Online (Sandbox Code Playgroud)

最后一个例子给了我

错误 CS0029:无法将类型 'string[ , ][]' 隐式转换为 'string?[ , ]?[]'

既然它适用于锯齿状数组(请参阅 参考资料b),为什么它不适用于多维数组呢?

R# 还告诉我

'c' 可以声明为不可空

string?[]?[]? c = new string[1][];
//          ^ redundant
Run Code Online (Sandbox Code Playgroud)

我知道编译器可以证明它c本身不为空,但我很困惑第三个?是多余的。鉴于锯齿状数组是从左到右创建的(即new int[2][]而不是 …

c# jagged-arrays multidimensional-array nullable-reference-types

9
推荐指数
1
解决办法
306
查看次数