PropertyInfo.getValue ()“객체는 대상 유형과 일치하지 않습니다.”
-
10-07-2019 - |
문제
나는 처음으로 반사를 파고 있고 나는 진정으로 붙어있다. 내가 생각할 수있는 모든 것을 검색했습니다. 나는 지금 내가되고 싶은 곳 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과 유형을 볼 수 있습니다. 필요한 것은 속성의 가치 만 있습니다! 이제 중단 점에 도달하면 targetexception을 얻고 오류 메시지는 "객체가 대상 유형과 일치하지 않습니다"라고합니다. 지금은 오전 1시에 아침에 난파되었습니다. 지금은 도움이 될 것입니다. MSDN과 Google을 검색하여 마지막으로 재미를 위해 검색했습니다.)
해결책
Me
참조 ObjectCompare
객체는 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)
다른 팁
나는 당신이 여기서 무엇을하려고하는지 잘 모르겠지만 나는 그것에 찌를 것입니다.
다음은 제가 등장한 코드입니다.
부름:
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