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
How to implement IEnumerable<T> with GetEnumerator()?
提问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();
}
}

