代码之家  ›  专栏  ›  技术社区  ›  kpollock

propertyinfo实例错误“object does not match target type”c上的setvalue#

  •  16
  • kpollock  · 技术社区  · 16 年前

    在以前的项目中,在不同的地方使用带有此代码的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);
    
        }
    

    希望有人能指出我的愚蠢之处????

    2 回复  |  直到 8 年前
        1
  •  19
  •   Daniel Sam    8 年前

    尝试:

    toProperty.SetValue(toObj,fromValue,null);
    

    你想把房子转手( toProperty )作为目标对象,而不是 toObj . 如需了解更多信息,请考虑 HyperDescriptor 从而大大降低了反射成本。

        2
  •  12
  •   Peter Lillevold Rene    16 年前

    应该是

    toProperty.SetValue(toObj,fromValue,null);