为什么要改变一个数组改变在C#中另一个数组? [英] Why changing one array changes another array in C#?
问题描述
我有一个二维阵列,即美国在C#。我建立一个一维数组,即子状态,各国。当我改变子状态,美国也发生了变化。我希望美国保持不变。谢谢
INT [] = SUBSTATE状态[0];
子状态[0] - = 1; //国发[0] [0]这里也发生了变化
在我的脑海里贵国的定义是:
INT [] []国家;
数组是引用类型,当你从国家数组复制元素你到了一个参考从第一清单和两个引用数组映射到相同的INT []数组。所以,当你改变阵列存储子阵您使用链接到同一个阵列。
最简单的解决方法是源阵列
的副本
VAR子状态=状态[0] .ToArray();
I have a two dimensional array namely States in C#. I build a one dimensional array, namely SubState, from States. When I change SubState, States changes too. I want States be unchanged. Thanks
int[] SubState = State [0];
SubState[0]-=1; //State[0][0] is also changed here
In my mind your State definition is:
int[][] State;
Array is a reference type and when you copy an element from the State array you get a reference to the array from the first list and the both references map to the same int[] array. So when you change array stored at SubArray you use a link to the same array.
The simple fix is a copy of the source array
var SubState = State[0].ToArray();
这篇关于为什么要改变一个数组改变在C#中另一个数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!