从一个方法中,我可以传递一个包含整数数组的结构,然后更改数组中的值。我不确定我是否完全理解为什么可以这样做。有人可以解释一下为什么我可以更改int []中存储的值吗?
private void DoIt(){
SearchInfo a = new SearchInfo();
a.Index = 1;
a.Map = new int[] { 1 };
SearchInfo b = new SearchInfo();
b.Index = 1;
b.Map = new int[] { 1 };
ModifyA(a);
ModifyB(ref b);
Debug.Assert(a.Index == 1);
Debug.Assert(a.Map[0] == 1, "why did this change?");
Debug.Assert(b.Index == 99);
Debug.Assert(b.Map[0] == 99);
}
void ModifyA(SearchInfo a) {
a.Index = 99;
a.Map[0] = 99;
}
void ModifyB(ref SearchInfo b) {
b.Index = 99;
b.Map[0] = 99;
}
struct SearchInfo {
public int[] Map;
public int Index;
}
最佳答案
在C#中,引用按值传递。传递给方法或存储在另一个类的实例中时,不会复制数组。 -传递对数组的引用。这意味着一种接收对数组的引用(直接或作为另一个对象的一部分)的方法可以修改该数组的元素。
与C ++之类的语言不同,您不能在C#中声明“不可变的”数组-但是,您可以使用诸如List之类的类,这些类具有只读包装器,以防止修改集合。
关于c# - 为什么不指定“ref”就可以从方法更改Struct的int []属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2610972/