C#中的值赋值

use*_*276 0 c# initialization

如果没有初始化,如何为数组赋值?

string[] s={"all","in","all"};

I mean why did not the compile show error?.Normally we need to 
initialize ,before assign values.
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 6

这只是语法糖.

这个:

string[] s = {"all","in","all"};
Run Code Online (Sandbox Code Playgroud)

被编译为相同的代码:

string[] tmp = new string[3];
tmp[0] = "all";
tmp[1] = "in";
tmp[2] = "all";
string[] s = tmp;
Run Code Online (Sandbox Code Playgroud)

请注意,在分配了s所有元素之前,不会分配数组引用.在我们宣布一个变量的特殊情况下,这并不重要,但在这种情况下它会有所不同:

string[] s = { "first", "second" };
s = new string[] { s[1], s[0] };
Run Code Online (Sandbox Code Playgroud)

对象和集合初始化器也是如此 - 变量仅在末尾分配.

  • 哦,我在John Skeet的代码中发现了一个错误!s未定义,第2行.我认为你的意思是tmp [0] ="all"; (3认同)
  • 有趣的是,int [] x = {1,2,3}不生成与int [] tmp = new int [3]相同的代码; tmp [0] = 1; tmp [1] = 2; tmp [2] = 3; int [] x = tmp.:-) (2认同)