通过 System.Reflection 获取集合。给出 TargetException: '对象不匹配

Obtaining a collection by System.Reflection. gives TargetException: 'Object does not match

我看了很多答案,但我仍然从下面的代码中得到 System.Reflection.TargetException: 'Object does not match target type'。请帮忙

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是returns“collection”,不匹配是怎么回事?

?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