2017-05-30 58 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. 
} 
相关问题