IEnumerable 给出错误异常处理无法读取列表

IEnumerable gives error exception handeling can't read list

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

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

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

如果您想在循环时修改集合,我会使用 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 货车集合而不是动物集合,这样您就可以遍历货车,并查看货车中的动物?

实际上你不能在循环时修改列表。 您需要创建另一个对象并分别添加马车和动物。 试试这个,如果你还不明白,请评论

您不能在使用 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 and here: https://gist.github.com/SeppPenner/a082062d3ce2d5b8196bbf4618319044.

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