C#,回报率范围内/集合 [英] C#: return yield range/collection
问题描述
我用的是收益率回报
关键字不少,但我觉得它缺乏时,我想的范围内添加到的IEnumerable
。下面是什么,我希望做一个简单的例子:
I use the yield return
keyword quite a bit, but I find it lacking when I want to add a range to the IEnumerable
. Here's a quick example of what I would like to do:
IEnumerable<string> SomeRecursiveMethod()
{
// some code
// ...
yield return SomeRecursiveMethod();
}
当然,这会导致一个错误,它可以做一个简单的循环来解决。有没有更好的办法做到这一点?环路感觉有点笨重。
Naturally this results in an error, which can be resolved by doing a simple loop. Is there a better way to do this? A loop feels a bit clunky.
推荐答案
没有,没有,我害怕。 F#的确实的与支持这一产量
,但在C#中没有等效 - 你必须使用循环,基本上是这样。对不起......我觉得你的痛苦。我在提到它我Edulinq博客文章之一,它会做的事情更简单。
No, there isn't I'm afraid. F# does support this with yield!
, but there's no equivalent in C# - you have to use the loop, basically. Sorry... I feel your pain. I mentioned it in one of my Edulinq blog posts, where it would have made things simpler.
请注意,使用收益回报递归可能是昂贵的 - 看到的韦斯·戴尔对迭代器了解更多信息(并提到了收益率的foreach四年前是正在考虑...)后
Note that using yield return recursively can be expensive - see Wes Dyer's post on iterators for more information (and mentioning a "yield foreach" which was under consideration four years ago...)
这篇关于C#,回报率范围内/集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!