vb.net - PropertyInfo.GetValue() "Object does not match target type."

标签 vb.net reflection propertyinfo

我第一次深入研究反射,我真的被困住了。我已经用谷歌搜索了我能想到的一切。我现在 90% 的地方是我想去的地方。

我正在尝试通过反射返回自定义类中的属性值。

这是我的类声明:

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 和 Google 到死,然后最后一次是为了好玩;)

最佳答案

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)

关于vb.net - PropertyInfo.GetValue() "Object does not match target type.",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/310518/

相关文章:

xml - 尝试使用 VB.net 序列化和反序列化复杂的 xml 文件

c# - Devexpress Treelist 添加对象只显示对象名称

c# - 如何确定属性是否被覆盖?

java - Java中如何限制开发者使用反射访问私有(private)方法和构造函数?

c# - 如何在运行时获取当前类名?

c# - 如何使用反射在派生类的属性之前获取基类的属性

c# - 获取类型的默认 PropertyDescriptors

.net - WPF RichTextBox – 迭代文本的单词并更改其内容和格式

c# - 如何通过反射到达属性后面的“对象”?

vb.net - Google YouTube API vb.net引用