Bab*_*bar 8 c# arrays initialization
我想在C#中编译以下代码:
String[] words = {"Hello", "Worlds"};
words = {"Foo", "Bar"};
Run Code Online (Sandbox Code Playgroud)
我收到编译错误,如:
Error 1 Invalid expression term '{'
Error 2 ; expected
Error 3 Invalid expression term ','
Run Code Online (Sandbox Code Playgroud)
另一方面,如果我尝试
String[] words = { "Hello", "Worlds" };
words = new String[] {"Foo", "Bar"};
Run Code Online (Sandbox Code Playgroud)
它汇编很好.根据MSDN,
int[] a = {0, 2, 4, 6, 8};
Run Code Online (Sandbox Code Playgroud)
它只是等效数组创建表达式的简写:
int[] a = new int[] {0, 2, 4, 6, 8};
Run Code Online (Sandbox Code Playgroud)
为什么不编译第一个代码示例?
Hen*_*man 10
正确,短初始化程序语法仅在声明中允许.不在正常的声明中.
String[] words = new string[]{ "Hello", "Worlds" }; // full form
String[] words = { "Hello", "Worlds" }; // short hand, special rule
words = {"Foo", "Bar"}; // not allowed
words = new String[] {"Foo", "Bar"}; // allowed, full form again
Run Code Online (Sandbox Code Playgroud)
只有当它用作声明的(rhs)部分时,才允许使用简写符号.
C#规范12.6数组初始值设定项
在字段或变量声明中,数组类型是声明的字段或变量的类型.在字段或变量声明中使用数组初始值设定项时,例如:int [] a = {0,2,4,6,8}; 它只是等效数组创建表达式的简写:int [] a = new int [] {0,2,4,6,8};
String[] words = { "Hello", "Worlds" };
Run Code Online (Sandbox Code Playgroud)
是宣言但是
words = {"Foo", "Bar"};
Run Code Online (Sandbox Code Playgroud)
不是.