列出<T>意外清除For循环

Imr*_*med 0 c# foreach class list

这个错误困扰了我!本质上,代码接收一个名为"Parking"的对象列表.我想将Parking类似的对象分组Title.为此,我考虑在列表中创建一个列表 - 这TerminalCollection是一个Parking对象列表和一个名称供参考.

为了帮助我,我创建了一个新的 - 临时terminal对象,它是一个Parking对象列表.每当我Parking在同一类别中找到一个对象时,我会将它添加到临时terminal对象,直到找到一个不适合的对象.发生这种情况时,我将terminal列表与名称组合以创建TerminalCollection对象.然后我通过将下一批类似的Parking对象添加到终端来重新开始该过程.

我发现的问题是,当我想terminal在创建TerminalCollection包含此列表副本的对象后清除列表时,列表也会从TerminalCollection对象中清除!! 我不知道为什么,因为我以为我正在创建一个新列表并为其分配一份副本terminal?为什么新列表与原始列表共享相同的内存terminal?有没有我误解的基本概念?非常感谢您提供任何帮助和建议来解决这个问题!:)

private static List<TerminalCollection> Terminals(List<Parking> input)
    {
        List<TerminalCollection> Terminals = new List<TerminalCollection>();
        List<Parking> terminal = new List<Parking>();
        int current = 0;
        int currentpos = 0;
        string currentname = "";
        bool clearbuffer = false;
        foreach (Parking attempt in input)
        {
            if (clearbuffer)
            {
                terminal.Clear();
                clearbuffer = false;
            }
            if (current != 0)
            {
                int checknew = int.Parse(Regex.Match(attempt.Title, @"\d+").Value);
                if (checknew - current == 0 && Regex.Match(attempt.Title, @"\d+").Index == currentpos)
                {
                    //Matches same terminal, so slot added in temporary terminal list  
                    terminal.Add(attempt);
                    currentname = Regex.Match(attempt.Title, @"^.*?\d+").Value;
                } 
                else
                {
                    //Clears and starts again (resets current and currentpos)
                    current = checknew;
                    currentpos = Regex.Match(attempt.Title, @"\d+").Index;
                    TerminalCollection final = new TerminalCollection();
                    final.Slots = terminal;
                    final.Name = currentname;
                    //One terminal added to global collection of terminals
                    Terminals.Add(final);
                    //Temporary terminal list cleared
                    clearbuffer = true;
                }
            }
            else { 
            //Gets first integer  
            current = int.Parse(Regex.Match(attempt.Title, @"\d+").Value);
            currentpos = Regex.Match(attempt.Title, @"\d+").Index;
            terminal.Clear();
            //Adds first element to start a new terminal
            terminal.Add(attempt);
            }
        }
        return null;
    }
Run Code Online (Sandbox Code Playgroud)

Bra*_*NET 7

Clear没有做出一个新的列表,而且也没有分配.您只需在循环之前创建一次列表,因此每个对象都将指向它.

您将此清单视为"其他"列表清除(实际上它们都是相同的列表).

您需要更改为:

if (clearbuffer)
{
   terminal = new List<Parking>();
   clearbuffer = false;
}
Run Code Online (Sandbox Code Playgroud)

现在每个迭代都有自己的列表对象,您不会看到它对其他实例的影响.

总而言之,考虑重新设计该循环,它真的令人困惑.

  • 看起来是另一个有兴趣了解参考类型的机会.:) (2认同)