【发布时间】:2010-10-26 21:51:42
【问题描述】:
可能重复:
Yield In VB.NET
在 C# 中,当编写返回 IEnumerble<> 的函数时,您可以使用 yield return 来返回枚举的单个项目,并使用 yield break; 表示没有剩余项目。做同样事情的 VB.NET 语法是什么?
来自NerdDinner 代码的示例:
public IEnumerable<RuleViolation> GetRuleViolations() {
if (String.IsNullOrEmpty(Title))
yield return new RuleViolation("Title required","Title");
if (String.IsNullOrEmpty(Description))
yield return new RuleViolation("Description required","Description");
if (String.IsNullOrEmpty(HostedBy))
yield return new RuleViolation("HostedBy required", "HostedBy");
if (String.IsNullOrEmpty(Address))
yield return new RuleViolation("Address required", "Address");
if (String.IsNullOrEmpty(Country))
yield return new RuleViolation("Country required", "Country");
if (String.IsNullOrEmpty(ContactPhone))
yield return new RuleViolation("Phone# required", "ContactPhone");
if (!PhoneValidator.IsValidNumber(ContactPhone, Country))
yield return new RuleViolation("Phone# does not match country", "ContactPhone");
yield break;
}
此convert C# to VB.NET tool 给出“YieldStatement 不受支持”错误。
【问题讨论】:
-
请注意,让步并不是回归,至少在大多数人的意思上不是回归(尽管它是在幕后实现的方式)。此外,您不需要在那里的收益中断。此外,您可能需要考虑将该代码从生成 RuleViolation 对象的枚举转换为生成 Func
委托的枚举。 -
使用yield让我想起了管道,因为调用代码可以在返回ienumerable的函数完成运行之前开始迭代ienumerable。很酷!
-
这是一个糟糕的例子,因为你公然不需要 yeild 来处理这样的事情:懒惰地确定违反规则有什么好处?把它们都塞进一个列表中,然后就可以完成了。这并不是说 yeild 没有用,但这只是一个不好的例子
-
@piers7,自从我发布这个问题以来,我学到了很多关于产量和迭代器的知识,我不得不同意你的看法。这只是我第一次看到产量,所以这就是我包含这个例子的原因。迄今为止我见过的最好的例子是一个没有预设大小限制的素数生成器(当然 MaxInt 除外)
-
对于 piers7,我不确定这是不是一个糟糕的例子。它根据需要评估条件,并在任何消耗它停止时停止。
标签: vb.net ienumerable iterator yield-return