如何在 Visual Basic 中使用像变量一样的字符串

问题描述:

我是 Visual Basic 的初学者,需要一些帮助.我有以下几点:

I´m a beginner in Visual Basic and I need some help. I have the following:

Dim var1 As String = "test1"
Dim newvar As String = "var1"
Dim othervar As String = ""

如何仅使用变量 newvar 使 othervar 变量的内容成为test1"?例如:

How can I make the contents of othervar variable be "test1" using only the variable newvar? For example:

othervar=newvar

变量othervar的内容为test1".如何在 Visual Basic 中使用字符串作为变量?我正在使用 Visual Studio Express 2012

And the contents of the variable othervar be "test1". How would one use a string as variable in Visual Basic? I´m using Visual Studio Express 2012

正如 peterG 提到的,可以使用 CallByName().但是,这要求在 Class(表单)级别将 var1 变量声明为 Public:

As peterG mentioned, CallByName() can be used. This however requires that the var1 variable be declared as Public at Class(Form) level:

Public Class Form1

    Public var1 As String = "test1"

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim newvar As String = "var1"
        Dim othervar As String = CallByName(Me, newvar, CallType.Get)
        MessageBox.Show(othervar)
    End Sub

End Class

如果 var1Private 那么你可以像这样使用 Reflection(它仍然必须是 Class 级别变量):

If var1 is Private then you can use Reflection like this (it still must be a Class level variable):

Imports System.Reflection
Public Class Form1

    Private var1 As String = "test1"

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim newvar As String = "var1"
        Dim FI As FieldInfo = Me.GetType.GetField(newvar, BindingFlags.Instance Or BindingFlags.Public Or BindingFlags.NonPublic)
        Dim othervar As String = FI.GetValue(Me)
        MessageBox.Show(othervar)
    End Sub

End Class

请注意,如果 var1 是局部变量,则不存在检索其值的方法.

Note that if var1 is a local variable then no method exists to retrieve its value.