code_junkie

PropertyInfo.GetValue() “Object does not match target type.”

Nov 12th, 2011
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.41 KB | None | 0 0
  1. Public Class Class2
  2. Private newPropertyValue2 As String
  3.  
  4. Public Property NewProperty2() As String
  5. Get
  6. Return newPropertyValue2
  7. End Get
  8. Set(ByVal value As String)
  9. newPropertyValue2 = value
  10. End Set
  11. End Property
  12. End Class
  13.  
  14. Public Class ObjectCompare
  15. Private _OriginalObject As PropertyInfo()
  16.  
  17. Public Property OriginalObject() As PropertyInfo()
  18. Get
  19. Return _OriginalObject
  20. End Get
  21. Set(ByVal value As PropertyInfo())
  22. _OriginalObject = value
  23. End Set
  24. End Property
  25.  
  26. Public Sub CompareObjects()
  27. Dim property_value As Object
  28.  
  29. For i As Integer = 0 To OriginalObject.Length - 1
  30. If OriginalObject(i).GetIndexParameters().Length = 0 Then
  31. Dim propInfo As PropertyInfo = OriginalObject(i)
  32.  
  33. Try
  34. property_value = propInfo.GetValue(Me, Nothing)
  35. Catch ex As TargetException
  36. End Try
  37. End If
  38. Next
  39. End Sub
  40. End Class
  41.  
  42. Dim test As New Class2
  43. test.NewProperty2 = "2"
  44.  
  45. Dim go As New ObjectCompare
  46. Dim propInf As PropertyInfo()
  47. propInf = test.GetType.GetProperties()
  48.  
  49. go.OriginalObject = propInf
  50.  
  51. go.CompareObjects()
  52.  
  53. Public Sub CompareObjects(ByVal It as Object)
  54. Dim property_value As Object
  55.  
  56. For i As Integer = 0 To OriginalObject.Length - 1
  57. If OriginalObject(i).GetIndexParameters().Length = 0 Then
  58. Dim propInfo As PropertyInfo = OriginalObject(i)
  59.  
  60. Try
  61. property_value = propInfo.GetValue(It, Nothing)
  62. Catch ex As TargetException
  63. End Try
  64. End If
  65. Next
  66. End Sub
  67.  
  68. go.CompareObjects(test)
  69.  
  70. Dim test As New Class2
  71. test.NewProperty2 = "2"
  72.  
  73.  
  74. Dim go As New ObjectCompare
  75. go.CompareObjects(test)
  76.  
  77. Public Class Class2
  78. Private newPropertyValue2 As String
  79.  
  80. Public Property NewProperty2() As String
  81. Get
  82. Return newPropertyValue2
  83. End Get
  84. Set(ByVal value As String)
  85. newPropertyValue2 = value
  86. End Set
  87. End Property
  88. End Class
  89.  
  90. Public Class ObjectCompare
  91.  
  92. Public Sub CompareObjects(ByVal MyType As Object)
  93.  
  94. For Each Prop In MyType.GetType().GetProperties()
  95. Dim value = Prop.GetValue(MyType, Nothing)
  96. Console.WriteLine(value)
  97. Next
  98. Console.ReadLine()
  99. End Sub
  100. End Class
Add Comment
Please, Sign In to add comment