c# - 如何为多个foreach实现正确的IEnumerator接口(interface)?

标签 c# .net ienumerable ienumerator

我有这样的代码:

        class T : IEnumerable, IEnumerator
        {
            private int position = -1;

            public T() { }

            public IEnumerator GetEnumerator() { return this; }

            public object Current { get { return position; } }

            public bool MoveNext()
            {
                position++;
                return (position < 5);
            }

            public void Reset() { position = -1; }
        }

//Using in code:
T t = new T();
foreach (int i in t)
 //to do something

在上面的代码中一切正常,但是当我使用 next 时:

foreach (int i in t)
   if (i == 2)
     foreach (int p in t)
       //print p
   else
       //print i

它打印(在括号中的第二个循环):0 1 (3 4) 2 而不是 0 1 (0 1 2 3 4) 2 3 4 我在 List 和 Collection 上测试了它,他们做对了。 我怎样才能达到我的需要?

最佳答案

你不能,因为你已经让你的代码表面成为一个单一的枚举器,这本身就是一个错误的 IMO。对我来说,更好的版本是:

class T : IEnumerable<int> {
    public IEnumerator<int> GetEnumerator() {
        int i = 0;
        while(i < 5) {
            yield return i;
            i++;
        }
    }
    IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); }
}

编译器将创建正确的设备以使用单独的枚举器实现此目的。

除非您正在为 .NET 1.1 编写代码,否则如果您发现自己手动编写一个枚举器,则很有可能您正在以艰难的方式完成它,并且错误地作为奖励.

如果您真的必须以艰难的方式做到这一点:

class T : IEnumerable<int>
{
    public T() { }

    public IEnumerator<int> GetEnumerator() { return new TEnumerator(); }
    IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); }
    private class TEnumerator : IEnumerator<int>
    {
        private int position = -1;
        public int Current { get { return position; } }
        object IEnumerator.Current { get { return Current; } }
        void IDisposable.Dispose() {}
        public bool MoveNext()
        {
            position++;
            return (position < 5);
        }
        public void Reset() { position = -1; }
    } 
}

这里的意义在于,TEnumerator 的不同实例允许相同 T 实例被单独迭代。

关于c# - 如何为多个foreach实现正确的IEnumerator接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7658449/

相关文章:

c# - 对集合的一部分执行接口(interface)方法时,项目从 Ienumerable 列表中消失

c# - 将枚举转换为 IEnumerable<SelectListItem> 问题

c# - C# 中的 yield return 是线程安全的吗?

c# - 在 C# 中从 Entity Framework 调用存储过程

c# - new() 约束对类定义有何作用?

c# - 从 C# COM 方法返回对象和内存所有权

.net - 需要安装Dnx运行时包

c# - 将按钮作为 GridView 中的最后一列

c# - 无法通过 WCFTestClient 测试自托管 WCF 服务

c# - 一个很好的 C# 集合