首先,很抱歉之前有人问过这个问题,但我就是找不到任何与之相关的东西。
string anElement = "World";
string[] col = new string[2] { "Hello", anElement };
anElement = "Jupiter";
Array.ForEach(col, Console.WriteLine);
// Output:
// Hello
// World
可以看到,为anElement
引用重新赋值并不会更新该值。
同样也适用于这个场景:
string[] col = new string[2] { "Hello", "World" };
string elementToUpdate = col[1];
elementToUpdate = "Jupiter";
Array.ForEach(col, Console.WriteLine);
如果所有的元素都存储为引用,为什么改变col[1]="Jupiter"
工作,而上面的不能?
试试下面的代码
string anElement = "World";
string[] col = new string[2] { "Hello", anElement };
col[1] = "Jupiter";
Array.ForEach(col, Console.WriteLine);
问题是您将值分配给anElement,而不是在需要进行更改的数组中获取项目
因为局部变量stringanElement未在任何执行路径中使用。试试下面的代码
string anElement = "World";
anElement = "Jupiter";
string[] col = new string[2] { "Hello", anElement };
Array.ForEach(col, Console.WriteLine);
// Output:
// Hello
// Jupiter