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

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

我要手动设置它的属性,如

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

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

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

尝试基于reflection的克隆:

 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; } 
  static void CopyProperties(object dest, object src) { foreach (PropertyDescriptor item in TypeDescriptor.GetProperties(src)) { item.SetValue(dest, item.GetValue(src)); } } 

使用AutoMapper

它非常容易使用。

AutoMapper入门

你可以通过Reflection做到这一点。

像这样的东西:

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

请参阅如何在.NET中对对象执行深层复制(特别是C#)?