2014-12-05 149 views
0

在javascript中我可以做將價值分配給變量基於另一個變量的值

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

設置基於另一個值的變量的值。所以在這種情況下,它將值33設置爲變量事物的值。

edit-然後這將設置MyVar的值爲33,如果我有另一個值的事情說otherVar它將設置otherVar的值爲33!

有什麼辦法可以在VB.Net中做到這一點?

+0

你可以使用粘土項目。 – 2014-12-05 14:13:39

+1

看看[這裏](http://stackoverflow.com/questions/6332097/using-a-variable-variable-name-in-visual-basic)和[這裏](http://stackoverflow.com/questions/15356108 /使用字符串作爲變量的名稱) – T30 2014-12-05 14:25:40

+1

在vb.net中使用'Dictionary(Of String,Integer)' – 2014-12-05 14:31:34

回答

0

下面是的WinForms,將與字段或屬性的工作使用反射的例子:

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 

如果你使用這個,不過,你可能有一個糟糕的設計到應用程序。