关于c#:’yield’关键字是一个语法糖吗?

Is 'yield' keyword a syntactic sugar ? What is its Implementation

本问题已经有最佳答案,请猛点这里访问。

Possible Duplicate:
yield statement implementation

我看过msdn文档,上面写着:

The yield keyword signals to the compiler that the method in which it appears is an iterator block. The compiler generates a class to implement the behavior that is expressed in the iterator block. In the iterator block, the yield keyword is used together with the return keyword to provide a value to the enumerator object.

因此,它意味着yield关键字是一种句法上的糖分,编译器要完成生成迭代器的繁重工作。(我说得对吗?)

那么,为这个语法糖生成的实现代码是什么?


生成的代码依赖于原始代码,但通常会生成一个状态机,用于跟踪集合的当前状态。

参见yield语句的实现,这个答案由eric lippert提供,这个博客文章由jon skeet提供。