枚举一个对象的属性并将其复制到另一个相同类型的对象 [英] Enumerate and copy properties from one object to another object of same type

查看:23
本文介绍了枚举一个对象的属性并将其复制到另一个相同类型的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用第三方控件将一些数据导出为不同的格式.该控件有一个属性ExportSettings.但它是只读的.

I use a third party control which exports some data to different formats. The control has a property ExportSettings. But it is read-only.

我必须手动设置它的属性,例如

I've to manually set its properties like

ctrl.ExportSettings.Paging = false;
ctr.ExportSettings.Background = Color.Red;

所以我从用户那里得到了 ExportSettings 对象,我想将它设置为控件.

So I get the ExportSettings object from the user and I want to set it to the control.

如何将其所有成员值复制到用户控件?

How can I copy all its member values to the user control?

推荐答案

尝试基于反射的克隆:

private object CloneObject(object o)
{
    Type t = o.GetType();
    PropertyInfo[] properties = t.GetProperties();

    Object p = t.InvokeMember("", System.Reflection.BindingFlags.CreateInstance, 
        null, o, null);

    foreach (PropertyInfo pi in properties)
    {
        if (pi.CanWrite)
        {
            pi.SetValue(p, pi.GetValue(o, null), null);
        }
    }

    return p;
}

这篇关于枚举一个对象的属性并将其复制到另一个相同类型的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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