从我读过的,
yield return <value>
在行执行时跳出函数。但是,Scott Guthrie的文字表明
var errors = dinner.GetRuleViolations();
成功提取所有规则违规的列表,即使GetRuleViolations是一长列
if(String.someFunction(text))
yield return new RuleViolation("Scary message");
if(String.anotherFunction(text))
yield return new RuleViolation("Another scary message");
这是如何运作的?
答案 0 :(得分:6)
它不会返回列表。它返回IEnumerable<RuleViolation>
。 yield return
会在iterator method中返回一个值。迭代器是一种在方法中生成元素序列的简单方法。
答案 1 :(得分:3)
yield关键字使用的是所谓的 懒惰的评价。这意味着什么 实际上就是以下任何事情 不会评估“收益率回报” 直到它被要求 枚举器。
另请参阅Eric Lippert关于Iterator Blocks的博客
Part 1
Part 2 - Why No Ref or Out Parameters
Part 3 - Why No yield in finally
Part 4 - Why No yield in catch
Part 5 - Push vs Pull
Part 6 - Why no unsafe code
答案 2 :(得分:0)
它的工作原理是因为yield return
向枚举器对象返回一个值,基本上为你自动化了一些管道代码(即它的语法糖)。它不会导致方法返回,即yield break
。
更多信息: