在以前的项目中,一直在使用带有此代码的 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);
}
希望有人能指出我在哪里愚蠢???