c# - 有关C#中IEnumerator.GetEnumerator的问题

标签 c# ienumerable ienumerator

我对IEnumerator.GetEnumerator()方法有疑问。

public class NodeFull
{
    public enum Base : byte {A = 0, C, G, U };
    private int taxID;
    private List<int> children;

    public int TaxID
    {
        get { return taxID; }
        set { taxID = value; }
    }

    public int this[int i]
    {
        get { return children[i]; }
        set { children[i] = value; }
    }

    public IEnumerator GetEnumerator()
    {
        return (children as IEnumerator).GetEnumerator();
    }

    public TaxNodeFull(int taxID)
    {
        this.taxID = taxID;
        this.children = new List<int>(3);
    }
}


当我尝试编译时,错误消息显示


  'System.Collections.IEnumerator'不包含'GetEnumerator'的定义,并且找不到扩展方法'GetEnumerator'接受类型为'System.Collections.IEnumerator'的第一个参数(是否缺少using指令或程序集引用?)


代码有什么问题吗?

提前致谢



感谢大伙们。我知道了。

最佳答案

它是IEnumerable.GetEnumerator()(或IEnumerable<T>.GetEnumerator()),而不是IEnumerator.GetEnumerator()IEnumerator上的成员是MoveNext()CurrentReset()(对于普通版本,是Dispose)。 IEnumerable是“可以迭代的对象”(例如列表),而IEnumerator表示该迭代中的当前状态-例如数据库游标。

您的类没有实现IEnumerableIEnumerable<T>本身有点奇怪。我希望这样的事情:

class NodeFull : IEnumerable<int>
{
    ... other stuff as normal ...

    public IEnumerator<int> GetEnumerator()
    {
        return children.GetEnumerator();
    }

    // Use explicit interface implementation as there's a naming
    // clash. This is a standard pattern for implementing IEnumerable<T>.
    IEnumerator IEnumerable.GetEnumerator()
    {
        // Defer to generic version
        return GetEnumerator();
    }
}

关于c# - 有关C#中IEnumerator.GetEnumerator的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3737135/

相关文章:

c# - 如何更改gridview中的列顺序?

c# - String 中的 ImageSource 不起作用?

c# - "is"关键字和 Equals 方法的覆盖

c# - 使用 yield return 的 IEnumerable 和递归

.net - IEnumerable<T> 表示 IEnumerable<T> 序列的 "rest"

c# - 使用 IEnumerable 检测修改

c# - Mono/Ubuntu - 冲突的定义

c# - FindAll 与 Where

c# - 如何检查 .NET 中的 IEnumerable<T> 是否以另一个 IEnumerable<T> 开头?

c# - 为什么脚本会忽略第一个 WaitForSeconds() 之后的部分?