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;
}
这篇关于枚举一个对象的属性并将其复制到另一个相同类型的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:枚举一个对象的属性并将其复制到另一个相同类型的对象
基础教程推荐
- 将数据集转换为列表 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 如果条件可以为空 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
