C#:收益率的回报范围/收藏 [英] C#: yield return range/collection

查看:108
本文介绍了C#:收益率的回报范围/收藏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用收益回报率关键字不少,但我觉得它缺乏时,我想一个范围添加到的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屋!

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