上的PropertyInfo实例错误&QUOT的SetValue;对象不匹配目标类型" C# [英] SetValue on PropertyInfo instance error "Object does not match target type" c#

查看:1504
本文介绍了上的PropertyInfo实例错误&QUOT的SetValue;对象不匹配目标类型" C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用此代码它在以前的项目不同的地方复制方法被(以处理有相同的命名属性,但不从一个共同的基类派生或实现一个共同的接口的对象)。

Been using a Copy method with this code in it in various places in previous projects (to deal with objects that have same named properties but do not derive from a common base class or implement a common interface).

工作,新的代码库的新的地方 - 现在它不能和的SetValue对象不匹配目标类型即使是在非常简单的例子...它上周的工作....

New place of work, new codebase - now it's failing at the SetValue with "Object does not match target type" even on very simple examples... and it worked last week....

    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);

    }



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

Hopefully someone can point out where I am being daft???

推荐答案

尝试:

toProperty.SetValue(toObj,fromValue,null);

您正试图在属性传递( toProperty )作为目标对象,而不是 toObj 。对于信息,如果你正在做大量的这个,也​​许是考虑 HyperDescriptor ,这可以极大地降低反映成本。

You are trying to pass in the property (toProperty) as the target object, instead of toObj. For info, if you are doing lots of this, maybe consider HyperDescriptor, which can vastly reduce the reflection cost.

这篇关于上的PropertyInfo实例错误&QUOT的SetValue;对象不匹配目标类型" C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆