如何在C#中未按值保存列表中的数组 [英] How to save array in list by value not reference in C#
本文介绍了如何在C#中未按值保存列表中的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想保存数组的当前状态,然后再更改该数组,但是当我将数组保存在列表中然后更改数组时,列表中的数组也会更改.这是示例代码,也是我代码的一部分:
I want to save my current state of array and later change that array but when I save my array in list and then change my array, array in list also changes. This is a sample code and a part of my code :
void main()
{
List<int[]> lisarr = new List<int[]>();
int[] a = new int[1];
a[0] = 1;
lisarr.Add(a);
a[0] = 10;
// at this time lisarr[0] also changes
....
}
如果您跟踪此代码,请注意,列表中的数组也发生了变化,但我不希望这样做.我该如何解决这个问题?
If you trace this code notice that my array in list also change, but I don't want this. How can I fix this problem?
推荐答案
添加数组的副本:
List<int[]> lisarr = new List<int[]>();
int[] a = new int[1];
a[0] = 1;
lisarr.Add(a.ToArray());
a[0] = 10;
这篇关于如何在C#中未按值保存列表中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文