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

Time:09-16

I've looked at lots of answers but I still get System.Reflection.TargetException: 'Object does not match target type' from the following code. Please help

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

When I query Prop, its PropertyType returns "collection", so what is the mismatch?

?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)}

CodePudding user response:

Your call to prop.GetValue uses a wrong parameter. You have to pass the object instance you want to get the value of, not the object type. So use cls as parameter:

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

See: https://dotnetfiddle.net/GmKOyt

  • Related