2013-09-30 300 views
11

我试图使用propertyInfo.SetValue()方法来设置对象属性值与反射,我得到异常“对象不匹配目标类型”。它没有任何意义(至少对我来说),因为我只是试图在一个字符串替换值的对象上设置一个简单的字符串属性。这里有一个代码片段 - 这是包含一个递归函数所以有一大堆更多的代码中,但这是胆量:C#反射 - 对象与目标类型不匹配

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”,都属于同一类型的这样做比较,这回真:

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

回答

17

您正试图设置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); 
+0

宾果 - 感谢清晰,简洁的代码示例。谢谢! –

3

你试图在BusinessObject的的属性的值设置为businessObject的类型,属性不是类型的另一个值。

要使此代码生效,replacementValue需要与piecesLeft[0]定义的字段的类型相同,并且显然不是那种类型。

4

我怀疑你只是想删除第二行。无论如何,它在那里做什么?您从获取属性的值,并将其设置为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); 
相关问题