从C#转换为VB.NET

本文关键字:VB NET 转换 | 更新日期: 2023-09-27 18:26:43

我知道VB.NET没有yield关键字,所以如何转换枚举的yield。在以下代码中?

    private static IEnumerable<int> Combinations(int start, int level, int[] arr)
    {
        for (int i = start; i < arr.Length; i++)
            if (level == 1)
                yield return arr[i];
            else
                foreach (int combination in Combinations(i + 1, level - 1, arr))
                    yield return arr[i] * combination;
    }

编辑:这是为.NET 2.0

知道吗?

谢谢,

从C#转换为VB.NET

当前版本的VB.Net确实支持yield关键字。我使用了从这里自动转换来生成此代码。

Private Shared Function Combinations(start As Integer, level As Integer, arr As Integer()) As IEnumerable(Of Integer)
    For i As Integer = start To arr.Length - 1
        If level = 1 Then
            yield Return arr(i)
        Else
            For Each combination As Integer In Combinations(i + 1, level - 1, arr)
                yield Return arr(i) * combination
            Next
        End If
    Next
End Function

如果不能使用yield,则需要一个列表来存储结果,然后在循环结束时返回。例如:

Private Shared Function Combinations(start As Integer, level As Integer, arr As Integer()) As IEnumerable(Of Integer)
    Dim result As New List(Of Integer)()
    For i As Integer = start To arr.Length - 1
        If level = 1 Then
            result.Add(arr(i))
        Else
            For Each combination As Integer In Combinations(i + 1, level - 1, arr)
                result.Add(arr(i) * combination)
            Next
        End If
    Next
    Return result
End Function

解决方案就是这个问题:VB.NET.中的Yield

如上所述,这个关键字现在是VB的一部分,如果您使用的是旧版本的VB.Net.

,请查看链接

我在互联网上找到的例子是

C#代码

public class List
{
//using System.Collections; 
public static IEnumerable Power(int number, int exponent)
{
    int counter = 0;
    int result = 1;
    while (counter++ < exponent)
    {
        result = result * number;
        yield return result;
    }
}
static void Main()
{
    // Display powers of 2 up to the exponent 8: 
    foreach (int i in Power(2, 8))
    {
        Console.Write("{0} ", i);
    }
}
}

/*输出:2 4 8 16 32 64 128 256*/

给出与Visual C#示例相同结果的VB.Net代码。

Option Strict On
Option Explicit On
Option Infer Off
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim results As System.Collections.Generic.IEnumerable(Of Integer)
    results = Power(2, 8)
    Dim sb As New System.Text.StringBuilder
    For Each num As Integer In results
        sb.Append(num.ToString & " ")
    Next
    MessageBox.Show(sb.ToString)
End Sub
Public Function Power(ByVal number As Integer, ByVal exponent As Integer) As System.Collections.Generic.IEnumerable(Of Integer)
    Dim result As New List(Of Integer)
    For index As Integer = 1 To exponent
        result.Add(Convert.ToInt32(Math.Pow(number, index)))
    Next
    Return result.AsEnumerable
End Function
End Class

参考-->http://msdn.microsoft.com/en-us/library/9k7k7cf0(v=vs.90).aspx