IEnumerable提供错误异常处理无法读取列表

问题描述 投票:1回答:3

我想要代码显示有多少货车以及每辆货车中有哪些动物。这是我的错误:

System.InvalidOperationException: "The collection has been changed. The inventory processing may not be performed. "

这是代码:

public IEnumerable<Animal> GetAnimals()
{
    return Animals.AsEnumerable();
}
public void Checker(List<Animal> listAnimals)
{
    foreach (Animal animal in listAnimals)
    {
        foreach (Wagon wagon in Wagons)
        {
            foreach (Animal wagonAnimal in wagon.GetAnimals())
            {
                if (wagon.StartCapacity <= wagon.MaxCapacity &&
                    animal.Formaat + wagon.StartCapacity <= wagon.MaxCapacity &&
                    wagonAnimal.Eater == Eater.carnivoor &&
                    animal.Eater == Eater.herbivoor &&
                    animal.Formaat >= wagonAnimal.Formaat)
                {
                    wagon.AddAnimal(animal);
                    Wagons.Add(wagon);    
                }
                else
                {
                     Wagon waggi = new Wagon();
                     waggi.AddAnimal(animal);
                     Wagons.Add(waggi);
                }
            }
        }

        Wagon wag = new Wagon();
        wag.AddAnimal(animal);
        Wagons.Add(wag);
    }
}

谁能给我一些关于这个问题的提示?

c# ienumerable
3个回答
0
投票

使用foreachin迭代时,您无法修改列表。

例:

foreach (Wagon wagon in Wagons)
{
    Wagon waggi = new Wagon();
    Wagons.Add(waggi);
}

不管用。

如果您使用例如

// This is needed to not get an endless loop (Because the length of the list
// increases after each time the Add() method is called to Wagons.)
int wagonCount = Wagons.Count;

for (int i = 0; i < wagonCount ; i++)
{
    Wagon waggi = new Wagon();
    waggi.AddAnimal(animal);
    Wagons.Add(waggi);
}

这会奏效。

我的代码的工作示例(就我能得到你想做的事情而言:https://dotnetfiddle.net/6HXYmI和这里:https://gist.github.com/SeppPenner/a082062d3ce2d5b8196bbf4618319044

我还建议根据Microsoft的定义检查您的代码样式:https://docs.microsoft.com/en-US/dotnet/csharp/programming-guide/inside-a-program/coding-conventions


1
投票

如果你想在循环时修改集合,我会使用List对象而不是IEnumerable

一些示例代码如下:

List<Wagons> Wagons = new List<Wagons>
Wagons.AddAnimal(animal1);

foreach(Animal animal in Wagons.GetAnimals(){
   animal.Eater = Eater.herbivore;
}

还看着你的代码:

if (wagon.StartCapacity <= wagon.MaxCapacity &&
    animal.Formaat + wagon.StartCapacity <= 
    wagon.MaxCapacity && wagonAnimal.Eater == Eater.carnivoor &&
    animal.Eater == Eater.herbivoor && animal.Formaat >= wagonAnimal.Formaat)
{
    wagon.AddAnimal(animal);
    Wagons.Add(wagon);
} else {
    wagon.AddAnimal(animal);
    Wagons.Add(wagon);
}

这个if / else语句完全相同的代码,所以你真的不需要if / else,你可以添加动物并添加旅行车。

最后,你的方法的参数不应该接受ListIEnumerable的货车集合,而不是动物,所以你可以穿过货车,看看货车里的动物?


0
投票

实际上你不能在循环时修改列表。您需要创建另一个对象并分别添加旅行车和动物。如果您还不了解,请尝试此操作并发表评论

© www.soinside.com 2019 - 2024. All rights reserved.