Enumerate and copy properties from one object to another object of same type

喜欢而已 提交于 2019-12-19 19:56:50

问题


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;

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?


回答1:


Try reflection-based cloning:

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



回答2:


  static void CopyProperties(object dest, object src)
  {
   foreach (PropertyDescriptor item in TypeDescriptor.GetProperties(src))
   {
    item.SetValue(dest, item.GetValue(src));
   } 
  }



回答3:


Use AutoMapper :

Its very easy to use.

Getting started with AutoMapper




回答4:


You can do it via Reflection.

Something like this:

Type exportSettingType = ctrl.ExportSettings.GetType();

foreach (PropertyInfo property in exportSettingType.GetProperties())
{
    object value = property.GetValue(ctrl.ExportSettings, null);
    property.SetValue(secondControl.ExportSettings, value, null);
}



回答5:


see How do you do a deep copy of an object in .NET (C# specifically)?



来源:https://stackoverflow.com/questions/4546381/enumerate-and-copy-properties-from-one-object-to-another-object-of-same-type

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!