3

我创建了一个实现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;
}

该实现基于此示例http://msdn.microsoft.com/en-us/library/system.collections.ienumerator.aspx

当我使用我的数组执行 foreach 循环时,我想防止集合修改(例如在循环内调用 Add())并抛出一个新的 InvalidOperationException。我怎么能做到这一点?

4

3 回答 3

5

你需要在你的班级中有一个版本 ID。在进入 时增加它Add。当您创建迭代器(在GetEnumerator()调用中)时,您会记住版本号 - 并且在每次迭代时,您将检查版本号是否仍然是开始时的版本号,否则抛出。

于 2011-11-16T15:22:14.803 回答
4

您可以将一个字段添加到您的集合中,您可以在每次修改集合时递增该字段。创建枚举器时,您将此字段的值存储在枚举器中。使用枚举器时,您验证字段的当前值是否与创建枚举器时存储的值相同。如果不是,你抛出一个InvalidOperationException.

于 2011-11-16T15:22:35.557 回答
1

You could use a list instead of temp array in your code and that will throw InvalidOperationException by default anyway. Secondly you could get by using generic version of IEnumerable and you may not have to do the hard work of creating a custom iterator.

于 2011-11-16T15:43:48.613 回答