根据另一个变量值为变量赋值

时间:2014-12-05 14:12:04

标签: vb.net variables

在javascript中我可以做到

var thing="MyVar";
var MyVar;
this[thing] = 33;

根据另一个值设置变量的值。所以在这种情况下,它将值33设置为变量的值。

编辑 - 然后将MyVar的值设置为33,如果我在其他值中有另一个值,则说otherVar会将otherVar的值设置为33!

有没有办法在VB.Net中这样做?

1 个答案:

答案 0 :(得分:0)

这是一个在WinForms中使用Reflection的示例,它将使用字段或属性:

Public Class Form1

    Private MyVar As Integer

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim thing As String = "MyVar"
        Dim value As Integer = 33
        Try
            Dim FI As System.Reflection.FieldInfo = Me.GetType.GetField(thing, Reflection.BindingFlags.IgnoreCase Or Reflection.BindingFlags.Instance Or Reflection.BindingFlags.Public Or Reflection.BindingFlags.NonPublic)
            If Not IsNothing(FI) Then
                FI.SetValue(Me, value)
            Else
                Dim PI As System.Reflection.PropertyInfo = Me.GetType.GetProperty(thing, Reflection.BindingFlags.IgnoreCase Or Reflection.BindingFlags.Instance Or Reflection.BindingFlags.Public Or Reflection.BindingFlags.NonPublic)
                If Not IsNothing(PI) Then
                    PI.SetValue(Me, value)
                Else
                    MessageBox.Show(value, "Field or Property not found!")
                End If
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Unable to Set Value")
        End Try

        Debug.Print("MyVar = " & MyVar)
    End Sub

End Class

但是,如果您正在使用此功能,则可能是您的应用程序设计不佳。