我的 C# 应用程序中的 List 有一些奇怪的问题。这一定是分配错误或者我做错了什么(我是普通的 C# 开发人员)。 让我举一个接近我的台词的例子:
List<String[]> MyPrimaryList = new List<String[]>();
List<String[]> MySecondaryList = new List<String[]>();
String[] array;
String arrayList = "one,two,three,four,five";
array = arrayList.Split(',');
MyPrimaryList.Add(array);
MySecondaryList.Add(array);
MyPrimaryList[0][0] += "half";
所以现在我希望 MyPrimaryList 中第一个数组中的第一个值在 MySecondaryList 中是“onehalf”和“one”。 但我的问题/问题是两个列表都更新为“onehalf”作为两个列表中第一个数组中的第一个值。
你有什么好的解释吗? :)
谢谢!!
最佳答案
String[] array;
是引用类型。您已将对此对象在内存中的位置的引用添加到两个列表,因此它们都包含相同的数据。
如果您需要第二个列表具有数组
的副本,那么您可以使用Array.Copy。 :
List<String[]> MyPrimaryList = new List<String[]>();
List<String[]> MySecondaryList = new List<String[]>();
String arrayList = "one,two,three,four,five";
String[] array = arrayList.Split(',');
String[] array2 = new string[5];
Array.Copy(array, array2, 5);
MyPrimaryList.Add(array);
MySecondaryList.Add(array2);
MyPrimaryList[0][0] += "half";
Console.WriteLine(MyPrimaryList[0][0]);
Console.WriteLine(MySecondaryList[0][0]);
这需要源数组、目标数组和长度——小心检查数组边界。
这个输出:
onehalf
one
由于每个列表现在都包含对不同数组的引用,因此您可以独立操作数组项。
关于List<String[]> 的 C# "funny"问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20119965/