13

The C# language specification (7.6.10.4) says, that there are tree kinds of array creation expressions:

new non-array-type [ expression-list ] rank-specifiersopt array-initializeropt
new array-type array-initializer
new rank-specifier array-initializer

The third one is intended for implicitly typed arrays:

var foo = new[] { 1, 2, 3 };

The question: is there any weighty reason to forbid to set array size explicitly in case of implicitly typed array?

It looks like asymmetric behavior, comparing with this syntax:

var foo = new int[3] { 1, 2, 3 };

Update.

A little clarification. The only advantage for combination of explicitly set array size and array initializer I can see, is the compile-time check for initializer length. If I've declared the array of three ints, the initializer must contain three ints.

I think, the same advantage is true for the implicitly typed arrays. Of course, to use this advantage or not to use is the personal preference.

4

2 回答 2

2

不需要排名说明符,因为它已经由初始化列表中的元素数量提供。

于 2013-01-30T05:56:43.027 回答
0

我认为这里的一个区别是,这种语法可以看作是首先创建一个类型化数组,然后填充它:

var foo = new int[3] { 1, 2, 3 };

这类似于我们可以在单个语句中声明和初始化其他数据类型的方式:

var list = new List<string>{ "a", "b", "c" };
var dict = new Dictionary<string, string>{ {"a", "b"}, {"c", "d"} };

第一条语句创建int[3]并填充它。第二个和第三个语句创建一个List<string>orDictionary<string, string>并填充它们。

但如果你这样做:

var foo = new[3] { 1, 2, 3 };

这不是一回事。没有像 a 这样的数据类型[3],因此与其他 2 个示例不同,这不是首先创建特定对象并填充它的情况。这是一种用于创建隐式类型数组的特殊语法,其中数组及其内容从大括号的内容中推断出来,然后创建。

我不知道为什么这种语法不应该存在,但我认为这是对你所看到的不对称的合理解释。

于 2013-01-30T06:45:46.893 回答