문제

I want to understand this topic and not just be able to throw down the syntax. I have a collection class called IGroupNode, which can take in a maximum of 8 children ISceneNodes.

internal class GroupNode : IGroupNode
{
    public string Name
    {
        get;
        private set;
    }

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

    public IEnumerable<ISceneNode> GetEnumerator()
    {
        //?
    }

As you can probably tell, it is a very simple collection class based off of a list. How can I make the implementation of IEnumerable here simply return the internal container’s enumerator? I am not sure how to do this in this very easy case.

Now I am running into trouble with this problem:

'Weber.SceneGraphCore.GroupNode' does not implement interface member 'System.Collections.IEnumerable.GetEnumerator()'. 'Weber.SceneGraphCore.GroupNode.GetEnumerator()' cannot implement 'System.Collections.IEnumerable.GetEnumerator()' because it does not have the matching return type of 'System.Collections.IEnumerator'.
도움이 되었습니까?

해결책

You can simply return children.GetEnumerator() in this case. (By the way your GroupNode object should implement IEnumerable and your GetEnumerator method should have the correct return type.)

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

In more general cases though you can iterate over something and call yield return for each element.

다른 팁

Since IList already implements IEnumerable<>, you can just return children.GetEnumerator() in your GetEnumerator() method.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top