gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 04:38:01 30 4
gpt4 key购买 nike

我正在尝试使用 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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com