PropertyInfo实例上的SetValue错误“对象与目标类型不匹配”c#

在以前的项目中的各个地方使用带有此代码的Copy方法(处理具有相同命名属性但不从公共基类派生或实现公共接口的对象)。

新的工作场所,新的代码库 – 现在它在SetValue失败,“对象与目标类型不匹配”,即使是非常简单的例子……它上周工作了….

public static void Copy(object fromObj, object toObj) { Type fromObjectType = fromObj.GetType(); Type toObjectType = toObj.GetType(); foreach (System.Reflection.PropertyInfo fromProperty in fromObjectType.GetProperties()) { if (fromProperty.CanRead) { string propertyName = fromProperty.Name; Type propertyType = fromProperty.PropertyType; System.Reflection.PropertyInfo toProperty = toObjectType.GetProperty(propertyName); Type toPropertyType = toProperty.PropertyType; if (toProperty != null && toProperty.CanWrite) { object fromValue = fromProperty.GetValue(fromObj,null); toProperty.SetValue(toProperty,fromValue,null); } } } } private class test { private int val; private string desc; public int Val { get { return val; } set { val = value; } } public string Desc { get { return desc; } set { desc = value; } } } private void TestIt() { test testo = new test(); testo.Val = 2; testo.Desc = "TWO"; test g = new test(); Copy(testo,g); } 

希望有人可以指出我在哪里愚蠢?

尝试:

 toProperty.SetValue(toObj,fromValue,null); 

您试图将属性( toProperty )作为目标对象而不是toObj 。 有关信息,如果您正在做很多这样的事情,可以考虑使用HyperDescriptor ,它可以大大降低reflection成本。

应该

 toProperty.SetValue(toObj,fromValue,null);