我想理解这个主题,而不仅仅是能够抛出语法。我有一个名为 IGroupNode 的集合类,它最多可以容纳 8 个子 ISceneNode。
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()
{
//?
}
您可能会说,它是一个非常简单的基于列表的集合类。我怎样才能使 IEnumerable 的实现在这里简单地返回 内部容器的枚举器?在这种非常简单的情况下,我不确定如何做到这一点。
现在我遇到了这个问题:
'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'.
最佳答案
在这种情况下,您可以简单地返回 children.GetEnumerator()
。 (顺便说一句,您的 GroupNode 对象应该实现 IEnumerable 并且您的 GetEnumerator 方法应该具有正确的返回类型。)
public IEnumerator<ISceneNode> GetEnumerator()
{
return children.GetEnumerator()
}
在更一般的情况下,尽管您可以迭代某些内容并为每个元素调用 yield return
。
关于c# - 为集合类实现 IEnumerable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19719712/