枚举一个对象的属性并将其复制到另一个相同类型的对象

Enumerate and copy properties from one object to another object of same type(枚举一个对象的属性并将其复制到另一个相同类型的对象)
本文介绍了枚举一个对象的属性并将其复制到另一个相同类型的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用第三方控件将一些数据导出为不同的格式.该控件有一个属性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;
}

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)