C#Reflection – 对象与目标类型不匹配

我正在尝试使用propertyInfo.SetValue()方法使用reflection设置对象属性值,并且我得到exception“对象与目标类型不匹配”。 它实际上没有意义(至少对我来说!)因为我只是试图在一个带有字符串替换值的对象上设置一个简单的字符串属性。 这是一个代码片段 – 它包含在一个递归函数中,所以有更多的代码,但这是胆量:

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

我已经通过执行此比较validation了“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); 

我怀疑你只想删除第二行。 无论如何它在做什么? 您 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); 

您尝试将businessObject上的属性值设置为另一个businessObject类型的值,而不是该属性的类型。

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