异常:集合已修改;枚举操作可能无法执行,在 clone() 时抛出

Exception : Collection was modified; enumeration operation may not execute, thrown while clone()

我正在尝试编写一个信息提供程序 class。我想通过 Clone() 提供深拷贝。所以我尝试的是:

public MyInfoClass Clone()
{
     MyInfoClass temp = (MyInfoClass)this.MemberwiseClone();
     foreach (MySystem sys in _mySystems)
     {
         temp.AddSys(sys);
     }
     return temp;
}

合集如下。每当集合至少有一个对象时,它就会抛出异常:

Collection was modified; enumeration operation may not execute.

private ObservableCollection<MySystem> _mySystems;

public ObservableCollection<MySystem> MySystems
{
    get{ return _mySystems; }
}

我尝试调试并观察到 ​​temp.AddSys(sys) 执行成功但在下一步抛出异常。你能帮忙吗?

this.MemberwiseClone() 制作成员的浅表副本,对于引用类型,两个对象具有相同的引用,因此您实际上是在枚举和修改同一个集合。您需要创建一个新集合并将项目添加到其中。

 MyInfoClass temp = (MyInfoClass)this.MemberwiseClone();
 temp._mySystems = new ObservableCollection<MySystems>();

 foreach (MySystem sys in _mySystems)
 {
     temp.AddSys(sys);
 }

 return temp;