0

我正在查看关于反射的https://stackoverflow.com/a/4132070/1529149 ..

特别是这个

Public Sub setProperty(ByVal obj As Object, ByVal propName As String, ByVal newValue As Object)
    Dim prop As Reflection.PropertyInfo = obj.GetType().GetProperty(propName)
    If Not prop Is Nothing AndAlso prop.CanWrite Then
    prop.SetValue(obj, newValue, Nothing)
    End If
End Sub

但我需要输入第一个变量作为字符串或动态的东西..

我看不到点设置

setProperty(FixedObject, "Dynamic Property", "Dynamic Results")

什么时候它会更强大

setProperty("Dynamic Object", "Dynamic Property", "Dynamic Results")

例如:

Dim billy As String = "Label"
Dim bob   As Integer = 1

setProperty(billy+bob, "Text", "Results")

创建 Label1.Text = "results"

对获得类似的东西有任何帮助吗?(ps 我知道我可能必须在某处将 bob 转换为字符串,但我还是 VB 的新手)

4

1 回答 1

0

我不明白你为什么要使用反射,但这有效:

Public Class Form1
    Private Sub Form1Load(sender As Object, e As EventArgs) Handles Me.Load
        Dim billy As String = "Label"
        Dim bob As Integer = 1
        Dim label As Object = Me.Controls(billy & bob)
        SetProperty(label, "Text", "Results")
    End Sub

    Public Sub SetProperty(obj As Object, propName As String, newValue As Object)
        Dim prop As Reflection.PropertyInfo = obj.GetType().GetProperty(propName)
        If Not prop Is Nothing AndAlso prop.CanWrite Then
            prop.SetValue(obj, newValue, Nothing)
        End If
    End Sub
End Class  
于 2013-03-29T20:38:17.960 回答