2017-05-30 54 views
-1

UPDATE當被問及爲什麼A不是隻是從D繼承而來,我應該說過,還會有其他類繼承自A。假設所有這些子類都從A如何在一個類的多個子類之間共享C#屬性代碼,但不是全部?

一些共享功能,我有一個有趣的情況,我認爲需要一些成分的方法。然而,現在我所擁有的是一些繼承,導致一個基類繼續成爲上帝階級。

public abstract class A 
    { 
     protected SameProperty {get; set;} 
     protected SharedMethod(); 
    } 

    public class B : A 
    { 
     //Uses SameProperty with some of its own variables 
     //SharedMethod used. 
    } 

    public class C : A 
    { 
     //Also uses SameProperty with some of ITS own variables 
     //SharedMethod used. 
    } 

    public class D : A 
    { 
     //Does not use SameProperty. Will never use it and there will be many other classes just like this. 
     //SharedMethod used. 
    } 

    public class E : A 
    { 
     //Does not use SameProperty either. 
     //SharedMethod used. 
    } 

在上面的例子中,B和C使用該屬性獲取和設置代碼,否則將在子類本身被複制。所以我使用A來分享它們之間的代碼。但是D和從A繼承的所有其他對象又怎麼樣呢?

我試圖做與SameProperty接口並將其添加到類B和C.然後,這使我想知道這會有所幫助,因爲我還是會最終實現屬性代碼的兩倍。

我也試圖使共享屬性爲一個靜態的靜態類,但這並不讓我在從B級和C需要進入靜態代碼的變量傳遞。

我不認爲我可以使用方法來代替屬性(這是什麼,Java?)。那麼,我怎樣才能做到這一點只是屬性?

感謝, 阿特金斯。

更新2我加了具體落實的問題性質,這是需要在某些子類的,但不是全部。對於那些好奇的人來說,這是Xamarin-iOS ViewController中的代碼。

我明白了一些用戶所提出的建議大約中間的子類A是B和C來自繼承的(比方說,F?)。

但是,假設從A繼承的子類D和E有它們自己的中間類G,但是也需要F的SameProperty。我如何在所有這些級別的繼承上做到這一點?當然,將SameProperty組合成其他類是唯一的方法?但是如何?

bool _bannerDisabled; 
public bool BannerDisabled 
{ 
    get 
    { 
     return _bannerDisabled; 
    } 
    set 
    { 
     if (BaseDisabledBanner != null && BaseDisabledBannerHeightConstraint != null) 
     { 
      _bannerDisabled = value; 
      BaseDisabledBannerHeightConstraint.Constant = _bannerDisabled ? _viewHeight : 0; 
      BaseDisabledBanner.Hidden = !_bannerDisabled; 
      View.LayoutIfNeeded(); 
     } 
    } 
} 
+3

不知道什麼此代碼的任何實際上是試圖做的,我們不可能上發表評論的架構是否合適什麼一個更好的選擇是。 – Servy

+1

爲什麼D不是你的基類,並且有繼承關係? –

+6

如果D''''''有問題並且繼承了'A'的任何東西,'D'沒有任何商業調用它自己作爲'A'的子類。 –

回答

2

也許這些方針的東西會做的伎倆:

public abstract class A0 
{ 
    //has common code that should be implemented by all 
} 
public abstract class B0 : A0 
{ 
    protected SameProperty {get; set;} 
} 
public class B : B0 
{ 
    //Uses SameProperty with some of its own variables 
} 
public class C : B0 
{ 
    //Also uses SameProperty with some of ITS own variables 
} 
public class D : A0 
{ 
    //Does not use SameProperty. Will never use it and there will be many other classes just like this. 
} 
相關問題