我想,也許你正在尋找一個拷貝構造函數模式。每個級別限定protected
構造函數副本相關屬性:
public class Parent
{
public string Name { get; set; }
public string City { get; set; }
//normal constructor
public Parent()
{
}
protected Parent(Parent copy)
{
this.Name = copy.Name;
this.City = copy.City;
}
}
的Child
將根據需要從Parent
繼承,它向下傳遞通過對拷貝構造,然後追加其新值:
public class Child : Parent
{
public string NewInfo { get; set; }
public Child(Parent copy)
: base(copy)
{
}
}
使用可能看起來像:
Parent parent = new Parent() { Name = "Name", City = "StackOverflow"};
Child child = new Child(parent) { NewInfo = "Something new!" };
Console.WriteLine(child.Name); //Name
Console.WriteLine(child.City); //StackOverflow
Console.WriteLine(child.NewInfo); //Something new!
從這樣做的好處是,你可以有多個層次與各級管理自己的財產遺產。
編輯:鑑於最近的評論:
的動機這個問題是在我得到的數據對象的 名單,並希望顯示這個數據,但一些 情況額外的領域,而不涉及基類。
也許是更好的方法,然後是包裝的基類:
public class Child
{
private readonly Parent WrappedParent;
public string NewInfo { get; set; }
public string Name
{
get { return WrappedParent.Name; }
set { WrappedParent.Name = value; }
}
public string City
{
get { return WrappedParent.City; }
set { WrappedParent.City = value; }
}
public Child(Parent wrappedParent)
{
this.WrappedParent = wrappedParent;
}
}
缺點是你必須重新聲明每個屬性,你不再是繼承(不能被認爲是)"Parent"
,但隨後你已經明確地「不接觸」基類了。如果這對你更好,可以將「父」屬性移動到接口中,但如果再次接觸基類,則必須將接口聲明添加到其類定義中。
是否有一個原因,你是從一個班轉移到另一個班的數據而不是直接進入'孩子'在首位? – 2013-02-19 18:47:01
爲什麼'Child'擴展'Parent'?小孩是否也是父母? (顯然這是可能的,但在這種情況下它感覺不對)。 'Child'應該具有'Parent'屬性嗎? – 2013-02-19 18:51:40
這個問題的動機是我在哪裏得到一個包含數據的對象列表,並且想要顯示這些數據但是有一些額外的字段,而沒有觸及基類。 – 2013-02-19 18:53:48