2013-07-20 233 views
2

假設我有3個類(父,子和女兒)。我想讓兒子和女兒使用Parent的Name getter方法,但是我想分別爲每個孩子類應用不同的屬性。覆蓋屬性屬性

public class Parent { 

private string name; 

public string Name { 
    get { return this.name; } 
    set { this.name = value != null ? value.trim() : null; } 
} 

} 

和兒子...

public class Son : Parent { 
    [SonAttribute] 
    public string Name { // keep parent behavior } 
    } 
} 

同爲女兒Name getter方法但[Daughter]屬性。

我可以這樣做嗎?

+0

@TGH - 感謝您的回答(看起來像被刪除了)。我選擇了p.s.w.g,因爲我沒有完全理解關於方法的'new'關鍵字。 –

回答

4

假設Name虛擬的Parent

public class Parent 
{ 
    public virtual string Name 
    { 
     get { return this.name; } 
     set { this.name = value != null ? value.trim() : null; } 
    } 
} 

你總是可以做到這一點:

public class Son : Parent 
{ 
    [SonAttribute] 
    public override string Name 
    { 
     get { return base.Name; } 
     set { base.Name = value; } 
    } 
} 

如果Name屬性是不是虛擬的,你將創建一個新的屬性,它的屬性基類型,這可能不是你想要的。詳細信息請參見Knowing When to Use Override and New Keywords (C# Programming Guide)

+0

兒子和女兒班的「名」字段是否屬於父親或孩子? –

+0

@Kevin私人領域將屬於'Parent'類。 –