当我枚举 IEnumerable 两次时,Resharper 提示可能存在多个 IEnumerable 枚举
。我知道,在某些数据库查询情况下,当您枚举两次时会出现异常。
我想在测试中重现这种行为。所以,我基本上希望抛出以下函数(因为多个枚举):
private void MultipleEnumerations(IEnumerable<string> enumerable)
{
MessageBox.Show(enumerable.Count().ToString());
MessageBox.Show(enumerable.Count().ToString());
}
我应该传递什么给它?所有列表、集合等都可以使用多个枚举。 即使是这种 IEnumerable 也不异常(exception):
private IEnumerable<string> GetIEnumerable()
{
yield return "a";
yield return "b";
}
谢谢。
最佳答案
您可能只想要一个自定义类:
public class OneShotEnumerable<T> : IEnumerable<T>
{
private readonly IEnumerable<T> _source;
private bool _shouldThrow = false;
public OneShotEnumerable(IEnumerable<T> source)
{
this._source = source;
}
public IEnumerator<T> GetEnumerator()
{
if (_shouldThrow) throw new InvalidOperationException();
_shouldThrow = true;
return _source.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
关于c# - 如何创建无法进行多个枚举的 IEnumerable<T> ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8321032/