2016-09-27 45 views
-1

代碼告訴話多,所以看這個:如何正確重寫,提升物業

public abstract class ViewObject: INotifyPropertyChanged { 
    public virtual string Id { 
    get { 
     return this.GetType().Name; 
    } 
    } 
} 

public class Object : ViewObject { 
    private string id = string.Empty; 
    public override string Id { 
    get { 
     return this.id; 
    } 
    set { 
     this.id = value; 
    } 
    } 
} 

什麼是實現在抽象類基實現的期望行爲的正確方法(是的,它應該有一個基本的實現這個,但不是其他的東西)?

我只能想到使用new keywork而不是override來簡單地隱藏基本實現,但是這是正確的嗎?

回答

-1

如果您使用new關鍵字,並且有人將您的派生對象轉換爲基類,則將調用基本實現,而不是派生的對象。爲了避免這種情況,需要override

但目前這是不可能的,因爲你的基類不支持setter。所以堅持override,並在基類中實現set方法,該方法只會拋出NotSupportedExecption

public abstract class ViewObject 
{ 
    public virtual string Id 
    { 
     get { return this.GetType().Name; } 
     set { throw new NotSupportedException(); } 
    } 
} 

public class Object : ViewObject 
{ 
    private string id = string.Empty; 
    public override string Id 
    { 
     get { return this.id; } 
     set { this.id = value; } 
    } 
} 
0

您已經在使用繼承。當方法名稱和參數相同時,Override方法很有用。 在這裏你可以使用方法重載。方法過載名稱的 相同,但參數不同。你也可以在繼承中使用。 我希望這有用