我正在尝试使用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" and
replacementValue`是相同的类型,返回true:
businessObject.GetType() == replacementValue.GetType()
答案 0 :(得分:23)
您正在尝试设置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);
答案 1 :(得分:6)
我怀疑你只想删除第二行。无论如何它在做什么?您从businessObject
引用的对象获取属性的值,并将其设置为新值businessObject
。因此,如果这确实是一个字符串属性,那么businessObject
的值将是之后的字符串引用 - 然后您尝试将其用作设置属性的目标!这有点像这样做:
dynamic businessObject = ...;
businessObject = businessObject.SomeProperty; // This returns a string, remember!
businessObject.SomeProperty = replacementValue;
那不行。
目前还不清楚replacementValue
是什么 - 无论是替换字符串还是业务对象来获取真正的替换值,但我怀疑你要么:
PropertyInfo fieldPropertyInfo = businessObject.GetType().GetProperties()
.FirstOrDefault(f => f.Name.ToLower() == piecesLeft[0].ToLower());
fieldPropertyInfo.SetValue(businessObject, replacementValue, null);
或者:
PropertyInfo fieldPropertyInfo = businessObject.GetType().GetProperties()
.FirstOrDefault(f => f.Name.ToLower() == piecesLeft[0].ToLower());
object newValue = fieldPropertyInfo.GetValue(replacementValue, null);
fieldPropertyInfo.SetValue(businessObject, newValue, null);
答案 2 :(得分:3)
您尝试将businessObject 上属性的值设置为businessObject
类型的另一个值,而不是该属性的类型。
要使此代码生效,replacementValue
需要与piecesLeft[0]
定义的字段类型相同,而且显然不是那种类型。