【问题标题】:Obtaining a collection by System.Reflection. gives TargetException: 'Object does not match通过 System.Reflection 获取集合。给出 TargetException: '对象不匹配
【发布时间】:2021-11-03 16:56:06
【问题描述】:

我查看了很多答案,但仍然从以下代码中得到 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返回“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)}

【问题讨论】:

    标签: .net vb.net reflection collections


    【解决方案1】:

    您对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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-10
      • 2021-12-19
      • 1970-01-01
      • 2011-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多