在C#中使用yield

我对c#中的yield关键字有一个模糊的理解,但我还没有看到在我的代码中使用它的必要性。 这可能源于对它缺乏了解。

那么, yield一些典型的好用法是什么?

yield只是让实现枚举器变得非常简单。 因此,如果您想编写一个返回IEnumerable的方法,则可以节省您必须创建枚举器类 – 您只需一次生成一个结果,编译器将负责详细介绍。

一个方便的案例是编写一个“无限枚举器”,调用者可以根据需要多次调用它。 这是一个生成无限系列Fibonacci数的例子: http : //chrisfulstow.com/fibonacci-numbers-iterator-with-csharp-yield-statements/ (嗯…… 理论上无限,但在实践中仅限于答:64)。

Yield实现了延迟加载的模式。 我建议从这个角度考虑它的用处。

例如。 在我正在开发的商业软件环境中,它可以带来降低数据库负载的优势。 您编写的代码可以从数据库中提取各种数据,但只会加载特定方案所需的部分。 如果用户没有深入UI,则不会加载相应的数据。

收益率用于普查员。 C#编译器自动暂停枚举循环的执行并将当前值返回给调用者。

 IEnumerable GetIntegers(int max) { for(int i = 1; i <= max) { yield return i; // Return current value to the caller } } 

- 或(更笨重) -

 IEnumerable GetIntegers(int max) { int count = 0; while(true) { if(count >= max) yield break; // Terminate enumeration count++; yield return count; // Return current value to the caller } } 

有关MSDN的更多详细信息。

当你只是想快速测试IEnumerable <>时,测试和模拟也很不错,比如…

 yield return somevalue; yield return someothervalue; yield return yetanotherone;