NerdDinner 示例的 Dining.GetRuleViolations 函数如何返回列表?

发布于 2024-07-29 22:31:30 字数 461 浏览 3 评论 0原文

根据我的阅读,

yield return <value> 

该行执行时就会跳出该函数。 然而,Scott Guthrie 的文本表明,

var errors = dinner.GetRuleViolations();

列表,也成功地提取了所有规则违规的列表。

if(String.someFunction(text))
    yield return new RuleViolation("Scary message");
if(String.anotherFunction(text))
    yield return new RuleViolation("Another scary message");

即使 GetRuleViolations 是一个很长的“这是如何工作的?”

From what I've read,

yield return <value> 

jumps out of the function the moment the line is executed. However, Scott Guthrie's text indicates that

var errors = dinner.GetRuleViolations();

successfully pulls out a list of all the rule violations even though GetRuleViolations is a long list of

if(String.someFunction(text))
    yield return new RuleViolation("Scary message");
if(String.anotherFunction(text))
    yield return new RuleViolation("Another scary message");

How does this work?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

日暮斜阳 2024-08-05 22:31:30

它不返回列表。 它返回一个 IEnumerableyield return 返回 迭代器方法。 迭代器是在方法中生成元素序列的一种简单方法。

It doesn't return a list. It returns an IEnumerable<RuleViolation>. yield return returns a value in an iterator method. An iterator is an easy way to generate a sequence of elements in a method.

海未深 2024-08-05 22:31:30

请参阅产量(C# 参考)

yield 关键字使用所谓的
懒惰评价。 这意味着什么
实际上是以下任何内容
不会评估“收益回报”
直到收到请求为止
枚举器。

另请参阅 Eric Lippert 关于迭代器块的博客。
第 1 部分
第 2 部分 - 为什么没有 Ref 或 Out 参数
第 3 部分 - 为什么最后没有收益
第 4 部分 - 为什么渔获量没有产量
第 5 部分- 推与拉
第 6 部分 - 为什么没有不安全代码

See yield (C# reference)

The yield keyword uses what's known as
lazy evaluation. What this means
practically is that anything following
a "yield return" will not be evaluated
until it is requested from the
enumerator.

Also have a look at Eric Lippert's blog on 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

北风几吹夏 2024-08-05 22:31:30

它之所以有效,是因为 yield return 返回一个值到枚举器对象,基本上为您自动化了一些管道代码(即它是语法糖)。 它不会导致方法返回,这将是 yield break

详细信息:

It works because yield return returns a value to an enumerator object, basically automating some plumbing code for you (i.e. it's syntactic sugar). It doesn't cause the method to return, that would be yield break.

More information:

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文