Yield in VB.NET

2019-01-02 18:35发布

C# has the keyword called yield. VB.NET lacks this keyword. How have the Visual Basic programmers gotten around the lack of this keyword? Do they implement they own iterator class? Or do they try and code to avoid the need of an iterator?

The yield keyword does force the compiler to do some coding behind the scenes. The implementation of iterators in C# and its consequences (part 1) has a good example of that.

标签: .net vb.net
8条回答
君临天下
2楼-- · 2019-01-02 19:00

VB.NET has the Iterator keyword https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/modifiers/iterator

Since Visual Studio 2012 it seems

查看更多
浪荡孟婆
3楼-- · 2019-01-02 19:02

The below code gives the output

2, 4, 8, 16, 32

In VB.NET,

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

In 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;
    int result=1;
    while (counter < 5)
    {
        result = result * 2;
        counter += 1;
        yield return result;
    }
}
查看更多
登录 后发表回答