c# - 如何创建无法进行多个枚举的 IEnumerable<T> ?

标签 c# ienumerable

当我枚举 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/

相关文章:

c# - 数组可以容纳的最大大小是多少?

asp.net-mvc - 为什么我无法通过 ViewData 或 Model 进行 foreach 操作?

c# - 无法将类型 'Task<System.Collections.Generic.IEnumerable<IClass>>' 隐式转换为 'System.Collections.Generic.IEnumerable<IClass>

c# - yield return 仅适用于 IEnumerable<T>?

c# - ExpectedException 属性无法显示预期结果 C#

c# - 这个简单的更新查询有什么问题?

c# - 我想创建一个具有任意索引的 IEnumerable 继承稀疏数组

c# - IEnumerable<List<T>> 到 List<T>

c# - 为什么 CheckBox.IsChecked 属性为 Nullable<bool>?

c# - 是否可以重新加载 XDocument 并保留对它的所有现有引用?