0

我了解 VB.NET 没有 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

任何想法?

谢谢,

4

3 回答 3

2

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

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
于 2013-08-06T10:30:21.053 回答
0

解决方案在这个问题中:Yield in VB.NET

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

于 2013-08-06T12:03:18.620 回答
-1

我在网上找到的例子是

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

于 2013-08-06T10:34:31.803 回答