克隆一个类
问题描述:
我有两个类包含相同的字段,但是从别处继承了一些属性,而另一个则没有。克隆一个类
我已经使用类“ZEUS_ResearchStocksHistory”创建了一个通用列表,但后来我需要将所有字段复制到另一个列表“ZEUS_ResearchStocksHistoryWithExcel”。我不希望循环遍历一个列表中的每个字段并填充另一个列表,或者编写某种linq连接,那么必须有更快的方式?
我不能在这两种情况下使用相同的类的原因是继承ExcelReport功能时,增加了我,当我显示此列表中的数据网格不想附加字段。
internal class ZEUS_ResearchStocksHistory
{
public String Amendment { get; set; }
public String AmendedBy { get; set; }
public String Sedol { get; set; }
public String Date { get; set; }
}
internal class ZEUS_ResearchStocksHistoryWithExcel : ExcelReport
{
public String Amendment { get; set; }
public String AmendedBy { get; set; }
public String Sedol { get; set; }
public String Date { get; set; }
}
这可能吗?
感谢
答
难道你看看在automapper?
CustomerViewItem customerViewItem =
Mapper.Map<Customer, CustomerViewItem>(customer);
答
退房Automapper,这是专门做正是这一点。 Automapper在NuGet上运行。
http://lostechies.com/jimmybogard/2009/01/23/automapper-the-object-object-mapper/
你可以做的简单的东西:
Mapper.CreateMap<ZEUS_ResearchStocksHistory, ZEUS_ResearchStocksHistoryWithExcel>();
var newObject = Mapper.Map<ZEUS_ResearchStocksHistory, ZEUS_ResearchStocksHistoryWithExcel>(oldObject);
或者,因为你说你有一个列表,你可以这样做:
var newList = oldList.Select(x => Mapper.Map<ZEUS_ResearchStocksHistory, ZEUS_ResearchStocksHistoryWithExcel>(x));
+0
大声笑两个家伙一样的想法;) – 2013-02-18 12:43:35
您可以实现你们班icloneable接口。 – Tomtom 2013-02-18 12:41:49
为什么不只是将数据网格设置为仅显示所需的字段? – juharr 2013-02-18 12:42:06
“它添加了其他字段,当我在数据网格中显示此列表时,我不想要这些字段。”这听起来像是一个显示问题:如果您可以隐藏数据网格中不需要的列,您的问题是否会得到解决?如果是这样,我强烈建议寻找显示问题的解决方案(他们往往更容易解决和理解)。 – dasblinkenlight 2013-02-18 12:43:29