我正在第一次深入思考,並且我真的被困住了。我搜索了我能想到的所有東西。我現在想成爲90%。PropertyInfo.GetValue()「對象與目標類型不匹配。」
我想通過反射返回自定義類中的屬性的值。
這裏是我的類聲明:
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和谷歌的死亡,然後在最後時間爲樂趣;)
我剛剛醒來,給了它一個去,它就像一個魅力!我認爲GetValue方法的第一個參數指向你想要從中檢索值的PropertyInfo對象。再次感謝! – StevenMcD 2008-11-22 07:49:17