在运行时循环遍历变量

时间:2016-05-06 12:39:10

标签: vb.net

有没有办法在运行时循环一组已定义的变量,而无需编写新的代码行来处理每个变量 例如,控制台应用程序的以下代码:

Module Module1

    Sub Main()
        Dim a!, b#, c%, d&, s$

        Console.WriteLine("a " & VarType(a).ToString)
        Console.WriteLine("b " & VarType(b).ToString)
        Console.WriteLine("c " & VarType(c).ToString)
        Console.WriteLine("d " & VarType(d).ToString)
        Console.WriteLine("s " & VarType(s).ToString)
        Console.ReadLine()
    End Sub
End Module

虚拟代码将是这样的:

for each Var in DefinedVariables 
'Do Something To the variable
next 

2 个答案:

答案 0 :(得分:1)

您可以使用MethodBody.LocalVariables检索方法体内声明的局部变量作为LocalVariableInfo实例的列表。不幸的是,您只能通过索引访问它们,因为名称未存储。你基本上得到变量类型,它被声明的序数,以及它是否被固定。优化甚至可以重新排序变量或完全消除变量。

Dim mi As MethodInfo =  GetType(Example).GetMethod("MethodBodyExample")
Dim mb As MethodBody = mi.GetMethodBody()
Console.WriteLine(vbCrLf & "Method: {0}", mi)

' Display the general information included in the 
' MethodBody object.
Console.WriteLine("    Local variables are initialized: {0}",  mb.InitLocals)
Console.WriteLine("    Maximum number of items on the operand stack: {0}",   mb.MaxStackSize)

' Display information about the local variables in the
' method body.
Console.WriteLine()
For Each lvi As LocalVariableInfo In mb.LocalVariables
    Console.WriteLine("Local variable: {0}", lvi)
Next

答案 1 :(得分:0)

正如我在评论中所说,使用一个集合。例如

    Dim letters As New List(Of String) From {"a", "b", "c", "d"}

    For Each letter In letters
        Console.WriteLine(letter)
    Next

编辑:

    Dim a As String = "a"
    Dim b As String = "b"
    Dim c As String = "c"
    Dim d As String = "d"
    Dim e As Integer = 123

    Dim variables As New List(Of Object) From {a, b, c, d, e}

    For Each value In variables
        Console.WriteLine(value.ToString)
    Next