【发布时间】:2014-08-11 03:58:01
【问题描述】:
我有一个 Item 和一个 AdvancedItem 子类(如果重要的话,全部由值类型组成):
public Item
{
public string A;
public bool B;
public char C;
...// 20 fields
}
public AdvancedItem : Item
{
public string Z;
}
很容易独立地创建一个 Item 或 AdvancedItem:
var item = new Item { A = "aa", B = true, C = 'c', ... };
var aItem = new AdvancedItem { A = "aa", B = true, C = 'c', ..., Z = "zz" };
现在,我只想通过单独提供字符串 Z 将 Item 转换为 AdvancedItem。为了实现这一点,我正在考虑使用构造函数。
尝试 A:
// annoying, we are not using the inheritance of AdvancedItem:Item
// so we will need to edit this whenever we change the class Item
public AdvancedItem(Item item, string z)
{
A = item.A;
B = item.B;
...;//many lines
Z = z;
}
尝试 B:
// to use inheritance it seems I need another constructor to duplicate itself
public Item(Item item)
{
A = item.A;
B = item.B;
...;//many lines
}
public AdvancedItem(Item item, string z) : base(Item)
{
Z = z;
}
有什么方法可以改进第二次尝试以避免编写多行 X = item.X? 或许可以解决自动克隆或自动复制 public Item(Item item) 所在的类的方法写成一行?
【问题讨论】:
-
我想知道你为什么要把一个项目变成一个高级项目。这似乎是一个奇怪的设计选择。
-
@mdebeus 事实上,在我的情况下,不同的序列化有不同的
[DataMember()]属性。我什至没有添加新字段,但我希望有不同的[DataMember()],具体取决于用于它的网络服务。也许还有另一种方法可以实现条件 DataMemberAttribute。
标签: c# inheritance constructor clone base-class