9

可能的重复:
VB.NET 中的 Yield

在 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;
}

将 C# 转换为 VB.NET 工具会给出“不支持 YieldStatement”错误。

4

6 回答 6

13

从语言语法级别来看,目前在 VB.Net 中没有等效于 C# 的 yield return。

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

于 2009-05-17T22:12:49.540 回答
8

新的Async CTP包括对YieldVB.NET 的支持。

有关用法的信息,请参阅Visual Basic 中的迭代器。

于 2011-05-05T14:37:38.047 回答
2

在这里查看我的答案:

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

于 2009-05-17T22:26:50.257 回答
0

在 VB.NET 中没有收益返回 :( 只需创建一个列表并返回它。

于 2009-05-17T22:00:37.213 回答
0

在幕后,编译器创建一个枚举器类来完成这项工作。由于 VB.NET 没有实现这种模式,因此您必须创建自己的 IEnumerator(Of T) 实现

于 2009-05-17T22:34:04.293 回答
0

下面给出输出:2、4、8、16、32

在 VB 中,

Public Shared Function setofNumbers() As Integer()

    Dim counter As Integer = 0
    Dim results As New List(Of Integer)
    Dim result As Integer = 1
    While counter < 5
        result = result * 2
        results.Add(result)
        counter += 1
    End While
    Return results.ToArray()
End Function

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    For Each i As Integer In setofNumbers()
        MessageBox.Show(i)
    Next
End Sub

在 C# 中

   private void Form1_Load(object sender, EventArgs e)
    {
        foreach (int i in setofNumbers())
        {
            MessageBox.Show(i.ToString());
        }
    }

    public static IEnumerable<int> setofNumbers()
    {
        int counter=0;
        //List<int> results = new List<int>();
        int result=1;
        while (counter < 5)
        {
          result = result * 2;
          counter += 1;
          yield return result;
        }
    }
于 2011-05-02T09:52:49.393 回答