下面是的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
如果你使用這個,不過,你可能有一個糟糕的設計到應用程序。
你可以使用粘土項目。 – 2014-12-05 14:13:39
看看[這裏](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
在vb.net中使用'Dictionary(Of String,Integer)' – 2014-12-05 14:31:34