通过 System.Reflection获取集合。给出目标异常:"对象不匹配



我看过很多答案,但我仍然得到System.Reflection.TargetException: '对象不匹配目标类型'从以下代码。请帮助

Imports System.Reflection
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim tc = New testClass
With tc
.col.Add(10.1)
.col.Add(10.2)
.col.Add(10.3)
Dim col As Collection = getProperty(tc, "col")
txtres.Text = col(2)
End With
End Sub
Public Function getProperty(cls As Object, name As String) As Object
Dim type As Type = cls.GetType()
Dim prop As PropertyInfo = type.GetProperty(name)
Dim col as collection = prop.GetValue(prop.PropertyType, Nothing)
Return col
End Function
Class testClass
Property col As New Collection
End Class
End Class

当我查询Prop时,它的PropertyType返回"集合",那么什么是不匹配?

?prop
{Microsoft.VisualBasic.Collection col}
Attributes: None {0}
CanRead: True
CanWrite: True
CustomAttributes: Count = 0
DeclaringType: {Name = "testClass" FullName = "Reflection_test.Form1+testClass"}
GetMethod: {Microsoft.VisualBasic.Collection get_col()}
IsSpecialName: False
MemberType: Property {16}
MetadataToken: 385875982
[Module]: {Reflection test.exe}
Name: "col"
PropertyType: {Name = "Collection" FullName = "Microsoft.VisualBasic.Collection"}
ReflectedType: {Name = "testClass" FullName = "Reflection_test.Form1+testClass"}
SetMethod: {Void set_col(Microsoft.VisualBasic.Collection)}

prop.GetValue的调用使用了错误的参数。您必须传递要获取其值的对象实例,而不是对象类型。所以使用cls作为参数:

Imports System
Imports System.Reflection
Imports Microsoft.VisualBasic
Public Module Module1

Public Sub Main()
Dim tc = New testClass
With tc
.col.Add(10.1)
.col.Add(10.2)
.col.Add(10.3)
End With
Dim col As Collection = getProperty(tc, "col")
Console.WriteLine(col.Count)
End Sub

Public Function getProperty(cls As Object, name As String) As Object
Dim type As Type = cls.GetType()
Dim prop As PropertyInfo = type.GetProperty(name)
Dim col as collection = prop.GetValue(cls)
Return col
End Function
Class testClass
Property col As New Collection
End Class

End Module

见:https://dotnetfiddle.net/GmKOyt

相关内容

  • 没有找到相关文章

最新更新