在C#中使用产量 [英] Using yield in C#

查看:166
本文介绍了在C#中使用产量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有收益率的模糊认识中的 C#,但我还没有看到需要在我的代码中使用它。这可能源于缺乏对它的理解。

I have a vague understanding of the yield keyword in c#, but I haven't yet seen the need to use it in my code. This probably comes from a lack of understanding of it.

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

So, what are some typical good usages of yield?

推荐答案

收益只是使得它非常容易实现一个枚举。所以,如果你想要写一个返回的IEnumerable℃的方法; T> 它可以节省您不必创建枚举器类 - 你只是收益一次一个结果和编译器需要照顾的幕后细节。

yield just makes it very simple to implement an enumerator. So if you wanted write a method that returns an IEnumerable<T> it saves you having to create the enumerator class - you just yield one result at a time and the compiler takes care of the details under the covers.

一个方便的情况下是写一个无限枚举调用方可以拨打多次,因为它需要。下面是产生无穷级数斐波那契数的例子: http://chrisfulstow.com/fibonacci - 值迭代器与 - CSHARP屈服报表/ (嗯... 理论上的无限的,但在实践中限于UINT64的大小)。

One handy case is to write an "infinite enumerator" that the caller can call as many times as it needs to. Here's an example that generates an infinite series of Fibonacci numbers: http://chrisfulstow.com/fibonacci-numbers-iterator-with-csharp-yield-statements/ (well... theoretically infinite, but in practice limited to the size of UInt64).

这篇关于在C#中使用产量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆