2008-11-21 53 views
7

我正在第一次深入思考,並且我真的被困住了。我搜索了我能想到的所有東西。我現在想成爲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和谷歌的死亡,然後在最後時間爲樂趣;)

回答

20

MeObjectCompare對象,這是比形成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) 
+0

我剛剛醒來,給了它一個去,它就像一個魅力!我認爲GetValue方法的第一個參數指向你想要從中檢索值的PropertyInfo對象。再次感謝! – StevenMcD 2008-11-22 07:49:17

1

我不太確定我知道你在這裏做什麼,但我會刺傷它。

這裏是我想出代碼:

調用

 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 
相關問題