我第一次深入研究反射技术,现在遇到了困难。我已经搜索了所有我能想到的内容,但是仍然无法解决问题。现在我已经完成了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,我需要的只是属性的值!现在当我到达断点时,我会得到一个TargetException,错误消息说“对象与目标类型不匹配。” 现在已经凌晨1点了,我筋疲力尽,现在需要任何帮助。我已经在MSDN和Google上搜索过很多次,最后一次只是为了好玩;)