19

在以前的项目中,一直在使用带有此代码的 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);

    }

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

4

2 回答 2

25

尝试:

toProperty.SetValue(toObj,fromValue,null);

您正在尝试将属性 ( toProperty) 作为目标对象传递,而不是toObj. 对于信息,如果你做了很多这样的事情,也许可以考虑HyperDescriptor,它可以大大降低反射成本。

于 2009-04-16T11:11:04.297 回答
12

应该

toProperty.SetValue(toObj,fromValue,null);
于 2009-04-16T11:13:17.693 回答