为什么 `new int[x]{}` 无效?
在 MonoDevelop 中,我有以下可以编译的代码:
int[] row = new int[indices.Count]{};
但是,在运行时,我得到:
Matrix.cs(53,53):错误 CS0150:A 预期值恒定 (CS0150) (测试矩阵)
我知道这个错误意味着什么,并迫使我调整数组大小:
int[] row = new int[indices.Count]{};
Array.Resize(ref row, rowWidth);
这是我必须处理的事情吗,因为我在 Linux 上使用 MonoDevelop?我确信在 .Net 3.5 下我能够使用包含数组宽度的变量来初始化数组。谁能确认这是孤立的吗?如果是这样,我可以向 bugzilla 报告该错误。
In MonoDevelop I have the following code which compiles:
int[] row = new int[indices.Count]{};
However, at run-time, I get:
Matrix.cs(53,53): Error CS0150: A
constant value is expected (CS0150)
(testMatrix)
I know what this error means and forces me to then resize the array:
int[] row = new int[indices.Count]{};
Array.Resize(ref row, rowWidth);
Is this something I just have to deal with because I am using MonoDevelop on Linux? I was certain that under .Net 3.5 I was able to initialize an array with a variable containing the width of the array. Can anyone confirm that this is isolated? If so, I can report the bug to bugzilla.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不能将数组创建语法与对象初始化语法混合在一起。删除
{ }
.当您编写时:
您正在创建一个大小为
indices.Count
并初始化为默认值的新数组。当您编写时:
您正在创建一个数组,然后将其内容初始化为值 [1,2,3,4]。数组的大小是根据元素的数量推断的。它的简写是:
数组仍然首先初始化为默认值,这种语法只是提供了一种简写,以避免必须自己编写这些额外的赋值。
You can't mix array creation syntax with object initialization syntax. Remove the
{ }
.When you write:
You are creating a new array of size
indices.Count
initialized to default values.When you write:
You are creating an array and then initializing it's content to the values [1,2,3,4]. The size of the array is inferred from the number of elements. It's shorthand for:
The array is still first initialized to defaults, this syntax just provides a shorthand to avoid havind to write those extra assignments yourself.
以下代码由于同样的原因在 Windows/.NET/LINQPad 上无法编译:
但是,从声明中删除对象初始化 (
{}
) 使其可以工作。The following code fails to compile for the same reason on Windows/.NET/LINQPad:
However, removing the object initialisation from the declaration (
{}
) makes it work.在 C# 中,如果要声明空数组,语法应为:
In C#, if you want to declare an empty array the syntax should be:
因为当您使用数组初始化语法并指定数组的大小时,
数组的大小是多余的信息。编译器可以从初始化列表推断大小。正如其他人所说,您可以创建空数组:
或使用初始化列表:
Because when you to use use array initialization syntax AND specify the size of the array
The size of the array is superfluous information. The compiler can infer the size from the initialization list. As others have said, you either create empty array:
or use the initialization list: