如果没有初始化,如何为数组赋值?
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)
这只是语法糖.
这个:
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)
对象和集合初始化器也是如此 - 变量仅在末尾分配.