【发布时间】:2022-11-27 04:48:50
【问题描述】:
首先,如果之前有人问过这个问题,我很抱歉,但我根本找不到与之相关的任何内容。
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" 有效而上面的无效?
【问题讨论】: