我将类型为double []的列表传递给类中的函数,使用tempList编辑函数内的值,然后返回已编辑的值。 但是正在编辑传递的原始列表,我不希望它们被编辑以匹配tempList。
这是代码。
List<double[]> newList = new List<double[]();
newList = myClass.myFunction(value, originalList);
// myClass
...
// myFunction
public List<double[]> myFunction(int value, List<double[]> myList)
{
List<double[]> tempList = new List<double[]>();
for (int i = 0; i < myList).Count; i++)
{
tempList.Add(myList[i]);
}
// Do stuff to edit tempList
return tempList;
}
答案 0 :(得分:4)
请记住,数组是引用类型。向tempList
添加数组时,只会添加对数组的引用,因此myList
和tempList
都会引用相同的double[]
个对象。
相反,您需要克隆数组:
for (int i = 0; i < myList.Count; i++)
{
tempList.Add((double[])myList[i].Clone());
}
答案 1 :(得分:1)
数组here double[]
是引用类型,因此行
tempList.Add(myList[i]);
正在添加对原始数组的引用。然后,当您编辑tempList时,您正在编辑原始数组。制作这样的副本:
tempList.Add(myList[i].ToArray());
答案 2 :(得分:1)
您正在将对数组的引用添加到新列表中,但不会复制每个数组的内容。您的副本应如下所示:
foreach (double[] item in myList)
{
double[] copy = new double[item.Length];
Array.Copy(item, copy);
templist.Add(copy);
}
答案 3 :(得分:0)
您遇到的问题是double[]
是引用类型,而不是值类型,因此当您将其添加到tempList
时,您要添加对原始对象的引用,而不是新对象。实际上,您需要在将double[]
添加到tempList
之前创建一个新的var tempList = myList.Select(x => x.ToArray()).ToList();
,这样您就不会处理原始对象了。
假设您可以使用LINQ,则无需循环。你可以这样做:
{{1}}
答案 4 :(得分:0)
这是因为集合/引用类型是通过引用传递的。 (实际上,保持变量是按值传递的,但所有变量都指向相同的参考值。)
有关详细说明,请阅读this SO Answer
如果您希望我的函数中的修改不反映在原始集合中,您必须复制/克隆它,然后传递给myFunction
。
实施例
newList = myClass.myFunction(value, (List<double>)originalList.Clone());
答案 5 :(得分:0)
tempList.Add(myList[i]);
表示将对索引i上的double []对象的引用添加到临时列表。 因此,如果您编辑该对象的值,您将获得两个列表的机会。
如果你想拥有一个不会互相影响的不同克隆列表,你必须这样做:
List<double[]> tempList = new List<double[]>();
for (int i = 0; i < myList).Count; i++)
{
double[] originalListItem = myList[i];
// the most important step here!!! - clone the originalListItem to clonedListItem
tempList.Add(clonedListItem);
}
// Do stuff to edit tempList
return tempList;
答案 6 :(得分:0)
您正在将double []引用复制到新列表,这是一个浅表副本。 您需要深层复制并创建新的双数组来编辑临时数组而不更改原始数组。
答案 7 :(得分:0)
您正在tempList中插入对数组的引用,而不是数组的副本。因此,如果更改tempList中的值,则表示您正在更改原始数组。
此代码将更好用:
for (int i = 0; i < myList.Count; i++)
{
var copy = new Double[myList[i].Length];
Array.Copy(myList[i], copy, myList[i].Length);
tempList.Add(copy);
}