使用反射设置值

时间:2016-06-20 14:07:13

标签: vb.net reflection system.reflection

我正在使用VB.NET。我创建了一个与我的程序类似的小规模测试项目。我试图说:getObjectType(object1)如果Object1.getType()=“ThisType”然后获取属性。每个对象都包含一个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

2 个答案:

答案 0 :(得分:1)

好吧,我很难看到您的代码示例如何应用于您的问题,但如果您只是询问如何使用反射设置对象的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

答案 1 :(得分:1)

您可以使用PropertyInfo.SetValue使用反射设置值。您还可以使用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属性的常用接口,或者只是键入检查和转换等等会更好。