我看了很多答案,但我還是從下面的代碼中得到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. 點擊
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)
結束 與
結束 子
Public Function getProperty(cls As Object, name As String) As Object 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
結束 功能
Class testClass
屬性 col As New Collection
結束 類別
結束 類
當我查詢Prop時,它的PropertyType回傳 "collection",那么是什么原因造成的不匹配?
?prop
{Microsoft.VisualBasic.Collection col}
屬性。無 {0}
可以讀取。True。
可以寫。True True
CustomAttributes: Count = 0
DeclaringType: {Name = "testClass" FullName = "Reflection_test.Form1 testClass"}。
GetMethod: {Microsoft.VisualBasic.Collection get_col()}。
IsSpecialName: False。
成員型別。Property {16]
MetadataToken: 385875982
[Module]: {Reflection test.exe}
名稱。"col"
屬性型別。{Name = "Collection" FullName = "Microsoft.VisualBasic.Collection"}。
反映的型別。{Name = "testClass"FullName = "Reflection_test.Form1 testClass"}反射型別:{Name = "testClass"}。
SetMethod: {Void set_col(Microsoft.VisualBasic.Collection)}。
uj5u.com熱心網友回復:
你對prop.GetValue的呼叫使用了一個錯誤的引數。你必須傳遞你想得到的物件實體的值,而不是物件的型別。因此,使用cls作為引數:
ImportsSystem
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)
結束 與
Dim col As Collection = getProperty(tc, "col")
Console.WriteLine(col.Count)
結束 Sub
Public Function getProperty(cls As Object, name As String) As Object 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[/span
Class testClass
屬性 col As New Collection
結束 類別
End Module
參見。https://dotnetfiddle.net/GmKOyt
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/308311.html
標籤:
上一篇:動態創建的代碼塊沒有啟動
