vb.net – PropertyInfo.GetValue()“对象与目标类型不匹配.”

前端之家收集整理的这篇文章主要介绍了vb.net – PropertyInfo.GetValue()“对象与目标类型不匹配.”前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我第一次深入反思,我真的陷入困境.我用谷歌搜索了我能想到的一切.我现在想成为90%.

我试图通过Reflection在自定义类中返回Property的值.

这是我的班级声明:

Public Class Class2
    Private newPropertyValue2 As String

    Public Property NewProperty2() As String
        Get
            Return newPropertyValue2
        End Get
        Set(ByVal value As String)
            newPropertyValue2 = value
        End Set
    End Property   
End Class

我写的通过反射查看类的类看起来像这样:

Public Class ObjectCompare
    Private _OriginalObject As PropertyInfo()

    Public Property OriginalObject() As PropertyInfo()
        Get
            Return _OriginalObject
        End Get
        Set(ByVal value As PropertyInfo())
            _OriginalObject = value
        End Set
    End Property

    Public Sub CompareObjects()
        Dim property_value As Object

        For i As Integer = 0 To OriginalObject.Length - 1
            If OriginalObject(i).GetIndexParameters().Length = 0 Then
                Dim propInfo As PropertyInfo = OriginalObject(i)

                Try
                    property_value = propInfo.GetValue(Me,Nothing)
                Catch ex As TargetException
                End Try   
            End If
        Next
    End Sub
End Class

我在property_value = propInfo.GetValue(Me,Nothing)行放置一个断点,看看结果是什么.

以下是我调用代码的方式:

Dim test As New Class2
test.NewProperty2 = "2"

Dim go As New ObjectCompare
Dim propInf As PropertyInfo()
propInf = test.GetType.GetProperties()

go.OriginalObject = propInf

go.CompareObjects()

通过反射我可以看到PropertyName和Type,我需要的只是Property的值!现在当我到达断点时,我得到一个TargetException并且错误消息显示“对象与目标类型不匹配”.它现在早上凌晨1点,我遇难了,现在任何帮助都会受到赞赏.我已经搜索过MSDN和谷歌,然后在最后一次寻找乐趣;)

Me指的是ObjectCompare对象,它与PropertyInfo对象派生的类(Class2)不同.您还需要传入一个从中检索PropertyInfo对象的类型的对象.
Public Sub CompareObjects(ByVal It as Object)
    Dim property_value As Object

    For i As Integer = 0 To OriginalObject.Length - 1
        If OriginalObject(i).GetIndexParameters().Length = 0 Then
            Dim propInfo As PropertyInfo = OriginalObject(i)

            Try
                property_value = propInfo.GetValue(It,Nothing)
            Catch ex As TargetException
            End Try   
        End If
    Next
End Sub

go.CompareObjects(test)
原文链接:https://www.f2er.com/vb/255416.html

猜你在找的VB相关文章