使用反射设置值

Setting Values Using Reflection

我正在使用 VB.NET。我创建了一个与我的程序类似的小规模测试项目。我想说的是:getObjectType(object1) if Object1.getType() = "ThisType" then get the properties。每个对象都包含一个 ID,我想这样做:Object1.Id = -1(我知道它不会那么短或容易)。我认为有一种方法可以通过使用类似的东西来做到这一点: Object1.SetValue(Value2Change, NewValue) 但这不起作用,我不确定如何准确地做到这一点。下面是我的代码。谢谢!

Module Module1

Sub Main()

    Dim Db As New Luk_StackUp_ProgramEntities

    Dim Obj1 As IEnumerable(Of Stackup) = (From a In Db.Stackups).ToList
    Dim Obj2 As IEnumerable(Of Object) = (From a In Db.Stackups).ToList

    Dim IdNow As Integer = Obj1(0).IdStackup
    Dim StackUpNow As Stackup = (From a In Db.Stackups Where a.IdStackup = IdNow).Single
    Console.WriteLine(StackUpNow)

    getInfo(StackUpNow)
    getInfo(Obj1(0), Obj1(0))
    areObjectsSame(Obj1(0), Obj1(67))
    switchObjects(Obj1(0), Obj2(1))
    getObjectValues(Obj2(55))


    Console.WriteLine("========================================")
    TestCopyObject(StackUpNow)
    ChangeObjectValues(StackUpNow)

    Console.ReadKey()
End Sub

Private Sub ChangeObjectValues(Object1 As Object)

    Console.WriteLine("Changing Object Values")
    Dim myField As PropertyInfo() = Object1.GetType().GetProperties()
    'Dim Index As Integer   'Did not find value
    'For Index = 0 To myField.Length - 1
    '    If myField(Index).ToString.Trim = "IdStackup" Then
    '        Console.WriteLine("Found the ID")
    '    End If
    'Next
    If Object1.GetType().Name = "Stackup" Then
        'Set the Value
    End If

End Sub

好吧,我很难看到你的代码示例如何应用于你的问题,但如果你只是想问如何使用反射设置对象的 ID,这段代码可能会对你有所帮助。诀窍是 属性 通常使用 set 和 get 方法处理。

Imports System.Web.UI.WebControls
Imports System.Reflection

Module Module1

Sub Main()
    Dim tb As New Label()

    Dim t As Type = tb.GetType()
    If TypeOf tb Is Label Then
        Dim mi As MethodInfo = t.GetMethod("set_ID")
        mi.Invoke(tb, New Object() {"-1"})
    End If

    Console.WriteLine(tb.ID)
    Console.ReadLine()
End Sub

End Module

您可以使用 PropertyInfo.SetValue to set the value using reflection. You could also use a LINQ SingleOrDefault 查询来简化查找正确 PropertyInfo 的过程,因此您可以这样做:

Private Sub ChangeObjectValues(Object1 As Object)

    Console.WriteLine("Changing Object Values")

    Dim t As Type = Object1.GetType()
    If t.Name = "Stackup" Then
        Dim myField As PropertyInfo = t.GetProperties() _
            .SingleOrDefault(Function(x) x.Name = "IdStackup")
        If myField IsNot Nothing Then
            Console.WriteLine("Found the ID")
            myField.SetValue(Object1, -1)
        End If
    End If

End Sub

从问题中不清楚您是否真的需要使用反射 - 也许一个通用接口来定义 id 属性,或者只是类型检查和转换等会更好。