IEnumerator 目的
我不太明白 C# Collections 中 IEnumerator 的用途是什么。 它的用途是什么?为什么要使用它?
我尝试在线查看 http://msdn.microsoft.com/ en-us/library/system.collections.ienumerator.aspx 但那篇文章没有多大意义。我问的原因是在Unity3d游戏引擎中,它与yield函数一起使用。我试图理解使用 IEnumerator 的原因。
I don't quite understand what the use of IEnumerator from the C# Collections is.
What is it used for and why should it be used?
I tried looking online at http://msdn.microsoft.com/en-us/library/system.collections.ienumerator.aspx
but that article doesn't make much sense. The reason I ask is in Unity3d Game Engine, it's used along with the yield function. I am trying to make sense of the reason for the use of IEnumerator.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当由类实现时,IEnumerator 接口允许使用内置的 foreach 语法对其进行迭代。
在需要迭代 IEnumerator 接口的类中,为控制对象循环的 GetEnumerator 函数定义了一个方法签名。
正如您在此示例中所看到的,yield 语句使您可以将控制权返回给调用者,而不会丢失其在枚举中的位置。当调用者到达 foreach 循环的下一个增量时,控制权将被传递回yield 语句之后的行。
The IEnumerator interface, when implemented by a class allows it to be iterated through using the built-in foreach syntax.
In the class that needs to be iterated for the IEnumerator interface defines a method signature for the GetEnumerator function that controls looping through the object.
As you can see in this example, the yield statement lets you return control to the caller without losing its place in the enumeration. Control will be passed back to the line after the yield statement when the caller hits the next increment of the foreach loop.
您很少显式使用 IEnumerator,但有很多扩展方法可以使用它,以及
foreach
。所有集合都实现它,它是迭代器模式的一个示例。You rarely use IEnumerator explicitly, but there are a lot of extension methods that work with it, as well as the
foreach
. All of the collections implement it, and it's an example of the Iterator pattern.它只是一个接口,允许对象执行操作以轻松迭代集合。您可以使用它来创建使用 foreach 构造或类似语法迭代自定义集合的对象。
It's quite simply just an interface which allows objects to perform operations for easily iterating over collections. You could use it to create objects which iterate over a custom collection with a foreach construct or similiar syntax.