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

调用Property.SetValue抛出System.Reflection.TargetException异常求助

问题根因排查与修复

核心错误1:SetValue参数传递错误

PropertyInfo.SetValue方法第一个参数要求传入要赋值的类实例对象,你当前代码传入的是类的类型对象baseObjectType,只有给静态属性赋值时才需要传类型对象,实例属性必须传实例本身,这就是抛出Object does not match target type异常的直接原因。

核心错误2:字段与属性查询不兼容

你提到diamond_0_quantity是类的字段而非属性,当前代码仅调用GetProperty查询属性元数据,无法匹配到字段,会直接走到属性不存在的分支,需要补充字段查询逻辑。

修正后的代码

Private Function SetClassPropertyValue(baseObject As Object, propertyOrFieldName As String, value As Object) As Boolean
    Try
        Dim baseObjectType As Type = baseObject.GetType()
        ' 先查询属性
        Dim propertyInfo As PropertyInfo = baseObjectType.GetProperty(propertyOrFieldName)
        If propertyInfo IsNot Nothing Then
            propertyInfo.SetValue(baseObject, value)
            Return True
        End If
        ' 属性不存在时查询字段
        Dim fieldInfo As FieldInfo = baseObjectType.GetField(propertyOrFieldName)
        If fieldInfo IsNot Nothing Then
            fieldInfo.SetValue(baseObject, value)
            Return True
        End If
        ' 都不存在时报错
        Display.ShowMessageBox("Fatal value set", $"Unable to set property or field '{propertyOrFieldName}' to '{value}'")
        Return False
    Catch ex As Exception
        Display.ShowMessageBox("Fatal value set", $"Unable to set property or field '{propertyOrFieldName}' to '{value}' due to exception '{ex}'")
        Return False
    End Try
End Function

其他优化说明

  • 你原有代码中定义的propertyType、valueType两个变量没有被使用,可以直接删除
  • 如果存在值类型不匹配的场景,可以补充类型转换逻辑,比如把传入的value转成目标属性/字段的类型后再赋值,避免类型转换异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 10:12:01