You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VB.NET通过System.Reflection获取Collection属性报TargetException错误求解

问题原因

你抛出System.Reflection.TargetException的核心错误出现在getProperty方法中PropertyInfo.GetValue的入参传递错误:

  • GetValue方法的第一个入参需要传入要读取属性的所属类实例(也就是你传入函数的cls对象,此处为testClass的实例),你当前错误传入了prop.PropertyType(即属性本身的类型Collection的Type对象),两者类型完全不匹配,因此触发了「对象与目标类型不匹配」的异常。
  • 你调试看到的PropertyType返回值为Collection是正常的,它仅代表该属性的返回值类型,和本次错误无关。
修正后的代码

只需要修改getProperty方法中GetValue的入参即可:

Public Function getProperty(cls As Object, name As String) As Object
    Dim type As Type = cls.GetType()
    Dim prop As PropertyInfo = type.GetProperty(name)
    ' 第一个参数改为传入类实例cls,而非prop.PropertyType
    Dim col as Collection = prop.GetValue(cls, Nothing)
    Return col
End Function

修改后运行即可正常获取到col集合的第二个元素10.2并赋值给txtres.Text。

内容的提问来源于stack exchange,提问作者ilens

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 16:54:02