我试图使用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);
应该是这样的:
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);