C# 反射 - 对象与目标类型不匹配

标签 c# reflection

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

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:

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

最佳答案

您正在尝试设置 propertyinfo 值的值。因为您要覆盖 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# 反射 - 对象与目标类型不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19101222/

相关文章:

c# - 使用 C# 实现代码模板

c# - 将 lambda 作为参数分配给通过反射调用的泛型方法

c# - EF Code First - 通过反射为所有实体调用 MapInheritedProperties()

c# - 重定向到完整域

c# - 使用 Validator 属性(或替代属性)来验证结构

c# - 通用类/方法的单元测试方法

C#拆分字符串

.net - 如何检测哪种 .NET 语言正在调用我的代码

java - java中的随机值取决于字段类型

asp.net-mvc - Web 中的反射和性能