C# 反射 - 对象与目标类型不匹配 [英] C# Reflection - Object does not match target type

查看:57
本文介绍了C# 反射 - 对象与目标类型不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 propertyInfo.SetValue() 方法通过反射设置对象属性值,但我收到异常对象与目标类型不匹配".这真的没有意义(至少对我来说!)因为我只是想在具有字符串替换值的对象上设置一个简单的字符串属性.这是一个代码片段 - 它包含在一个递归函数中,所以还有更多的代码,但这是胆量:

I'm trying to use the propertyInfo.SetValue() method to set an object property value with reflection, and I'm getting the exception "Object does not match target type". It doesn't really make sense (at least to me!) as I'm just trying to set a simple string property on an object with a string replacement value. Here's a code snippet - this is contained within a recursive function so there's a bunch more code, but this is the guts:

PropertyInfo fieldPropertyInfo = businessObject.GetType().GetProperties().FirstOrDefault(f => f.Name.ToLower() == piecesLeft[0].ToLower());
businessObject = fieldPropertyInfo.GetValue(businessObject, null);

fieldPropertyInfo.SetValue(businessObject, replacementValue, null);

我已经通过做这个比较验证了 businessObject" 和replacementValue` 都是相同的类型,结果返回 true:

I've verified that businessObject" andreplacementValue` are both the same type by doing this comparison, which returned true:

businessObject.GetType() == replacementValue.GetType()

推荐答案

您正在尝试设置 propertyinfo 值的值.因为您正在覆盖 businessObject

You're trying to set the value of the propertyinfo value's. Because you're overwriting the businessObject

PropertyInfo fieldPropertyInfo = businessObject.GetType().GetProperties()
                                 .FirstOrDefault(f => f.Name.ToLower() == piecesLeft[0].ToLower());

// The result should be stored into another variable here:
businessObject = fieldPropertyInfo.GetValue(businessObject, null);

fieldPropertyInfo.SetValue(businessObject, replacementValue, null);

应该是这样的:

PropertyInfo fieldPropertyInfo = businessObject.GetType().GetProperties()
                                 .FirstOrDefault(f => f.Name.ToLower() == piecesLeft[0].ToLower());

// also you should check if the propertyInfo is assigned, because the 
// given property looks like a variable.
if(fieldPropertyInfo == null)
    throw new Exception(string.Format("Property {0} not found", f.Name.ToLower()));

// you are overwriting the original businessObject
var businessObjectPropValue = fieldPropertyInfo.GetValue(businessObject, null);

fieldPropertyInfo.SetValue(businessObject, replacementValue, null);

这篇关于C# 反射 - 对象与目标类型不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆