【问题标题】:Why does the value of this List change when I change another List? [duplicate]为什么当我更改另一个列表时,此列表的值会发生变化? [复制]
【发布时间】:2021-01-16 04:06:33
【问题描述】:

您好,我已经遇到过类似的问题,但不幸的是我不知道如何解决它。我有一个List<int> tmpList 和一个List<int> tmpSpeicherListe,我想在其中复制我的tmpList,这样我就可以编辑我的tmpList 并在需要时重置它。

我想在 for 循环中多次编辑 tmpList 并在每次循环重复时重置它,但是如果我在位置 x 删除一个 tmpList 的值,它也会在位置 x 删除 tmpSpeicherListe 的值。那么我应该将List<int> tmpSpeicherListe = tmpList; 的声明放在哪里,否则错误在哪里?

ps:这只是我代码的一部分

//...

List<int> tmpSpeicherListe = tmpList;            //copy tmpList
int basisPosition = 2;
int counter2 = 0;

while(counter2 + 2 < tmpList.Count - 1)
{
    basis = tmpList[basisPosition];
    for (int m = 1; m < tmpList.Count - basisPosition; m++)
    {
        int speicher = tmpList[basisPosition + m];
        bool vorhanden = false;
        for (int n = 0; n < intKombinierbar[basis].Length; n++)
        {
            if (intKombinierbar[basis][n] == speicher)
            {
                vorhanden = true;
                break;
            }
        }
        if(vorhanden == false)
        {
            tmpList.RemoveAt(basisPosition + m);        //edit tmpList BUT tmpSpeicherListe changes too
        }
    }


    if(tmpList.Count <= i)
    {
        tmpList = tmpSpeicherListe;            //reset tmpList
        counter2++;
        basisPosition = 2 + counter2;
                                                
    }
    else if (basisPosition == tmpList.Count - 2)
    {
        großeKombinationen.Add(tmpList);
        tmpList = tmpSpeicherListe;            //reset tmpList
        counter2++;
        basisPosition = 2 + counter2;
                                                
    }
    else
    {
        basisPosition++;
    }
}
//...

【问题讨论】:

    标签: c#


    【解决方案1】:

    你应该克隆List。您将tmpSpeicherListe 的引用设置为tmpList 的引用。你可以这样克隆。

    List<int> tmpSpeicherListe = new List<int>(tmpList);
    

    【讨论】:

    • 如果您打算从tmpList 中删除对象,它也会使用这种方法从tmpSpeicherListe 中删除它们。
    猜你喜欢
    • 2017-01-14
    • 2018-09-06
    • 2021-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-20
    • 1970-01-01
    • 2018-04-21
    相关资源
    最近更新 更多