C# 编辑列表问题<;双[]>;在c中#

C# 编辑列表问题<;双[]>;在c中#,c#,list,C#,List,我将double[]类型的列表传递给类中的函数,使用模板列表编辑函数中的值,然后返回编辑后的值。 但是正在传递的原始列表也在编辑中,我不希望它们被编辑为与圣殿骑士匹配 这是代码 List<double[]> newList = new List<double[](); newList = myClass.myFunction(value, originalList); // myClass ... // myFunction public List<double[]&

我将double[]类型的列表传递给类中的函数,使用模板列表编辑函数中的值,然后返回编辑后的值。 但是正在传递的原始列表也在编辑中,我不希望它们被编辑为与圣殿骑士匹配

这是代码

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;
}

List newList=newList请记住数组是引用类型。将数组添加到
templast
时,只添加对数组的引用,因此
myList
templast
都引用相同的
double[]
对象

相反,您需要克隆阵列:

for (int i = 0; i < myList.Count; i++)
{
   tempList.Add((double[])myList[i].Clone());
}
for(int i=0;i
您遇到的问题是
double[]
是引用类型,而不是值类型,因此当您将其添加到
模板列表中时,您添加的是对原始对象的引用,而不是新对象。实际上,在将其添加到
templast
之前,您需要创建一个新的
double[]
,这样您就不会处理原始对象

假设可以使用LINQ,则不需要循环。您可以执行以下操作:

var tempList = myList.Select(x => x.ToArray()).ToList();

这是因为集合/引用类型是通过引用传递的。(实际上,保持变量是按值传递的,但所有变量都指向同一个引用)

有关详细说明,请阅读

如果您希望my Function中的修改不会反映在原始集合中,则必须复制/克隆它,然后传递到
myFunction

范例

newList = myClass.myFunction(value, (List<double>)originalList.Clone());
newList=myClass.myFunction(value,(List)originalList.Clone());

数组,
这里的double[]
是一种引用类型,因此

tempList.Add(myList[i]);
正在添加对原始数组的引用。然后,当您编辑tempList时,您正在编辑原始数组。像这样复制一份:

tempList.Add(myList[i].ToArray());
foreach (double[] item in myList)
{
    double[] copy = new double[item.Length];
    Array.Copy(item, copy);
    templist.Add(copy);
}
意味着您将索引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;
List templast=newlist();
对于(int i=0;i
您正在将对数组的引用添加到新列表中,但没有复制每个数组的内容。您的副本应如下所示:

tempList.Add(myList[i].ToArray());
foreach (double[] item in myList)
{
    double[] copy = new double[item.Length];
    Array.Copy(item, copy);
    templist.Add(copy);
}

您正在将double[]引用复制到新列表,这是一个浅副本。
您需要一个深度副本并创建新的双数组来编辑临时数组而不更改原始数组。

您是在模板列表中插入对数组的引用,而不是数组的副本。因此,如果您在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);
    }
for(int i=0;i
是的,但代码一开始看起来很可疑。克隆阵列很少是正确的做法。实际上,你的问题是什么,你想做什么?您可以编辑原始列表,无需创建新列表。