PropertyInfo.GetValue()“对象不匹配目标类型。”
-
10-07-2019 - |
题
我挖入反射首次和我忠实地卡住。我GOOGLE了所有我能想到的。我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()
通过反思,我可以看到属性名和类型,我需要的是物业的价值!现在,当我到了断点,我得到一个TargetException和错误消息说“对象不匹配目标类型。”它现在在早上凌晨1点,我破坏了,任何帮助,现在,将不胜感激。我搜索MSDN和谷歌的死亡,然后在最后时间为乐趣;)
解决方案
Me
指ObjectCompare
对象,这比从该PropertyInfo
对象被衍生(Class2
)类不同。你还需要通过在从中检索的<=>对象的类型的对象。
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)
其他提示
我真的不知道我知道你正试图在这里做的,但我会在它有刺。
下面是我所想出的代码:
<强>调用强>:
Dim test As New Class2
test.NewProperty2 = "2"
Dim go As New ObjectCompare
go.CompareObjects(test)
<强>类强>:
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
Public Sub CompareObjects(ByVal MyType As Object)
For Each Prop In MyType.GetType().GetProperties()
Dim value = Prop.GetValue(MyType, Nothing)
Console.WriteLine(value)
Next
Console.ReadLine()
End Sub
End Class
不隶属于 StackOverflow