0

I'm getting a frustrating error in my code which does not allow me to implement IEnumerable for a class I have created. Let me post the code, as it always makes more sense and it is very short here...

[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(); //***
    }
...
}

And the interface:

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

And finally, the error message (it is actually pretty descriptive):

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

Just what have I done wrong here? All I did was take my collection class, which is based off of a list, and return the List's GetEnumerator method. But then, in the error message, it is saying I have not implemented IEnumerable... I thought that returning GetEnumerator would be sufficient, but I cannot tell in this case.

4

1 回答 1

3

IEnumerable<T>继承自IEnumerable(非通用版本)。任何时候你实现泛型方法,你还需要提供一个非泛型对应物。

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

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

除了现有方法之外,只需将其添加到类中即可。

于 2013-11-01T02:41:18.137 回答