如何在Visual Basic中使用类似变量的字符串

时间:2013-11-18 00:16:57

标签: vb.net visual-studio-2012

我是Visual Basic的初学者,我需要一些帮助。 我有以下内容:

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

如何仅使用变量othervarnewvar变量的内容设为“test1”?例如:

othervar=newvar

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

2 个答案:

答案 0 :(得分:2)

正如peterG所提到的,可以使用CallByName()。但是,这需要在{strong>类(表单)级别将var1变量声明为公共

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

如果var1 私有,那么您可以像这样使用反射(它仍然必须是级别变量):

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是局部变量,则不存在检索其值的方法。

答案 1 :(得分:0)

如果您是VB的初学者,您可能会发现此网站很有用:Visual Basic Language Features

如果你想将一个字符串变量设置为另一个变量所在的相同字符串,你只需要使用你已经拥有的语法:

Module Module1

Sub Main()
    Dim var1 As String = "test1"
    Dim otherVar As String = var1

    Console.WriteLine(var1) 'test1
    Console.WriteLine(otherVar) 'test1

    var1 = "test2"

    Console.WriteLine(var1) 'test2 
    Console.WriteLine(otherVar) 'test1 (notice this did not change) 


End Sub

End Module