我能在VB.NET中实现IEnumerable函数的收益率返回吗?

2024-05-15 21:04:08 发布

您现在位置:Python中文网/ 问答频道 /正文

Possible Duplicate:
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 is unsupported”错误。


Tags: newstringnetreturniftitlerequireddescription
3条回答

在VB.Net中,从语言语法的角度来看,目前没有等价于C#的收益率。

然而,BillMcCarthy最近在MSDN杂志上发表了一篇关于如何在VB.NET9.0中实现类似模式的文章

请看我的答案:

总结一下:
VB.Net没有yield,但是C#通过将代码转换到幕后的状态机来实现yield。VB.Net的Static关键字还允许您在函数中存储状态,因此理论上您应该能够实现一个类,该类允许您在用作方法的Static成员时编写类似的代码。

新的Async CTP包括对VB.NET中Yield的支持。

有关用法的信息,请参见Iterators in Visual Basic

相关问题 更多 >