【问题标题】:How to implement IEnumerable using a return call to IEnumerator? C#如何使用对 IEnumerator 的返回调用来实现 IEnumerable? C#
【发布时间】:2013-11-01 02:38:47
【问题描述】:

我的代码中出现了一个令人沮丧的错误,它不允许我为我创建的类实现 IEnumerable。让我发布代码,因为它总是更有意义,而且在这里很短......

[Serializable]
internal class GroupNode : IGroupNode, IEnumerable<ISceneNode>
{
    public string Name
    {
        get;
        private set;
    }

    const int NumberOfChildren = 8;
    #region Member variables
    private IList<ISceneNode> children = new List<ISceneNode>(NumberOfChildren);
    #endregion

    public IEnumerator<ISceneNode> GetEnumerator()
    {
        return children.GetEnumerator(); //***
    }
...
}

还有界面:

 public interface IGroupNode : ISceneNode, IEnumerable<ISceneNode>
{
    void AddChild(ISceneNode child);
}

最后,错误信息(实际上非​​常具有描述性):

Error   1   'Project.SceneGraphCore.GroupNode' does not implement interface member 'System.Collections.IEnumerable.GetEnumerator()'. 'Project.SceneGraphCore.GroupNode.GetEnumerator()' cannot implement 'System.Collections.IEnumerable.GetEnumerator()' because it does not have the matching return type of 'System.Collections.IEnumerator'.    C:\Users\Ian\documents\visual studio 2012\Projects\ISceneGraph\SceneGraph\GroupNode.cs  11  20  SceneGraph

我在这里做错了什么?我所做的只是获取基于列表的集合类,并返回列表的 GetEnumerator 方法。但是,在错误消息中,它说我没有实现 IEnumerable... 我认为返回 GetEnumerator 就足够了,但在这种情况下我无法判断。

【问题讨论】:

    标签: c# ienumerable ienumerator


    【解决方案1】:

    IEnumerable&lt;T&gt; 继承自 IEnumerable(非通用版本)。任何时候实现泛型方法时,您还需要提供非泛型对应项。

    如果您只是在 Visual Studio 中右键单击该界面,它会自动为您生成函数,但您可以根据需要手动添加它。

    IEnumerator IEnumerable.GetEnumerator()
    {
        return children.GetEnumerator();
    }
    

    只需将它添加到类中除了现有的方法

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-13
      • 1970-01-01
      • 2010-12-17
      • 2016-08-24
      相关资源
      最近更新 更多