C# 如何使用 GetEnumerator() 实现 IEnumerable<T>?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11313373/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 17:22:10  来源:igfitidea点击:

How to implement IEnumerable<T> with GetEnumerator()?

c#ienumerable

提问by Colonel Panic

I would like my type to implement IEnumerable<string>. I tried to follow C# in a Nutshell, but something went wrong:

我希望我的类型实现IEnumerable<string>. 我试图在 Nutshell 中遵循 C#,但出了点问题:

public class Simulation : IEnumerable<string>
{
    private IEnumerable<string> Events()
    {
        yield return "a";
        yield return "b";
    }

    public IEnumerator<string> GetEnumerator()
    {
        return Events().GetEnumerator();
    }
}

But I get the build error

但我收到构建错误

Error 1 'EventSimulator.Simulation' does not implement interface member 'System.Collections.IEnumerable.GetEnumerator()'. 'EventSimulator.Simulation.GetEnumerator()' cannot implement 'System.Collections.IEnumerable.GetEnumerator()' because it does not have the matching return type of 'System.Collections.IEnumerator'.

错误 1 ​​'EventSimulator.Simulation' 未实现接口成员 'System.Collections.IEnumerable.GetEnumerator()'。“EventSimulator.Simulation.GetEnumerator()”无法实现“System.Collections.IEnumerable.GetEnumerator()”,因为它没有“System.Collections.IEnumerator”的匹配返回类型。

采纳答案by Filip Ekberg

You're missing IEnumerator IEnumerable.GetEnumerator():

你失踪了IEnumerator IEnumerable.GetEnumerator()

public class Simulation : IEnumerable<string>
{
    private IEnumerable<string> Events()
    {
        yield return "a";
        yield return "b";
    }

    public IEnumerator<string> GetEnumerator()
    {
        return Events().GetEnumerator();
    }

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

回答by NominSim

IEnumerable requires that you implement both the typed and generic method.

IEnumerable 要求您实现类型化和泛型方法。

In the community section of the msdn docsit explains why you need both. (For backwards compatibility is the reason given essentially).

在 msdn文档的社区部分,它解释了为什么您需要两者。(为了向后兼容是本质上给出的原因)。