收益率回报的长度
有没有办法在不保留计数器变量的情况下从函数内获取收益率返回的数量?例如?
IEnumerable<someobject> function
{
for loop
yield return something
int numberreturned = ....
}
Is there a way to get the number of yield returns from within a function without keeping a counter variable? For instance?
IEnumerable<someobject> function
{
for loop
yield return something
int numberreturned = ....
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这将违背
收益回报
的目的。使用
yield return
意味着您想要实现一个生成器(MSDN 将其称为迭代器块),即一个即时计算其返回的每个值的对象嗯>。根据定义,生成器可能是无限的,因此控制可能永远不会离开您的for
循环。流的工作方式相同。要计算流的长度,您必须耗尽它,并且您可能永远不会从这样做中返回。毕竟,数据可能来自无限的来源(例如/dev/zero) 。
That would defeat the purpose of
yield return
.Using
yield return
means you want to implement a generator (MSDN calls that an iterator block), i.e. an object that computes every value it returns on the fly. By definition, generators are potentially infinite, and therefore control might never leave yourfor
loop.Streams work the same way. To compute the length of a stream, you have to exhaust it, and you might never return from doing that. After all, the data could come from an infinite source (e.g. /dev/zero).
不。如果没有计数器,这是不可能的——无法从函数本身内部访问返回的流。 (如果可能的话,我想知道它会带来什么样的奇怪的语义/怪癖?)
但是,使用计数器这是完全可以的(如果有问题的话),即使问题不希望这样的响应;-)记住这一点当需要流中的下一项(迭代器)时,构造的形式是围绕调用闭包的“魔法”——也就是说,流控制离开并重新进入按要求
收益回报
。快乐编码。
No. This is not possible without a counter -- there is no way to access the returned stream from within the function itself. (If it were possible, I wonder what sort of strange semantics/quirks it would entail?)
However, this is perfectly okay (if questionable) with a counter, even if the question does not desire such a response ;-) Remember that this form of construct is "magic" around closures invoked when the next item in the stream (iterator) is required -- that is, flow control leaves and re-enters at the
yield return
as required.Happy coding.
您可以在 IEnumerable<> 上使用扩展方法 count你的函数返回
you could use the extension method count on the the IEnumerable<> that your function returns
您可以使用
IEnumerable.Count
扩展方法!我认为 yield return 旨在让编译器使用其后面的语句隐式构建基本迭代器。
如果您想要一个更复杂的迭代器,那么您可以以更明确的方式实现它。
You could use the
IEnumerable.Count
extension method!I think that
yield return
is intended for the compiler to implicitly build a basic iterator using the statement that follows it.If you want a more complex iterator then you might implement that in a more explicit manner.