Spa*_*tum 3 c# foreach iterator invalidoperationexception
我创建了一个实现IEnumerable(T)和自定义IEnumerator(T)的自定义集合.
我还在自定义集合中添加了一个Add()方法,如下所示:
public void Add(T item)
{
T[] tempArray = new T[_array.Length + 1];
for (int i = 0; i < _array.Length; i++)
{
tempArray[i] = _array[i];
}
tempArray[_array.Length] = item;
_array = tempArray;
tempArray = null;
}
Run Code Online (Sandbox Code Playgroud)
该实现基于此示例http://msdn.microsoft.com/en-us/library/system.collections.ienumerator.aspx.
当我使用我的数组进行foreach循环时,我想阻止集合修改(比如在循环中调用Add())并抛出一个新的InvalidOperationException.我怎么能这样做?
您需要在班级中拥有版本ID.在进入时增加它Add.当您创建一个迭代器(在GetEnumerator()调用中)时,您会记住版本号 - 并且在每次迭代时,您将检查版本号是否仍然是它的开头,否则抛出.
| 归档时间: |
|
| 查看次数: |
540 次 |
| 最近记录: |