替代的“多重”继承方式

时间:2013-02-27 21:15:36

标签: c#-4.0

我的情况如下:

    public class A : class B
    {
         public SomeMethodA()
         {
              //.... do some logics here
              SomeMethodB();
         }

         private SomeMethodB()
         {
              //.... do some logics here
         }

    }

class B : class C

class X : class Y
{
     public SomeMethodA()
     {
          //.... do some logics here
          SomeMethodB();
     }

     private SomeMethodB()
     {
          //.... do some logics here
     }
}

class Y : class Z

A类与X类完全相同。现在的问题是:我如何集中这个方法,以便我的代码有DRY(不要重复自己)而不修改/触摸类Y,Z和B类,C? B,C,Y和Z类是我们的遗留代码,我们不会尝试更改/修改这些类。

任何想法?

1 个答案:

答案 0 :(得分:3)

自您编辑并使其更清晰。我相信这会奏效。只需创建一个X和A将继承的公共类。

public abstract class Common
{
     public SomeMethodA()
     {
          //.... do some logics here
          SomeMethodB();
     }

     private SomeMethodB()
     {
          //.... do some logics here
     }
}

public class A : Common { /* some other methods */ }
public class B : A { /* some other methods */ } //B inherits A
public class C : B { /* some other methods */ } //C inherits B

public class X : Common { /* some other methods */ }
public class Y : X { /* some other methods */ } //Y inherits Z
public class Z : Y { /* some other methods */ } //Z inherits Y

2ND编辑:

public class Common
{
     public void SomeMethodA()
     {
          //.... do some logics here
          SomeMethodB();
     }

     private void SomeMethodB()
     {
          //.... do some logics here
     }
}

然后在A和X类中,做这样的事情:

public void SomeMethod() {
    Common c = new Common();
    c.SomeMethodA();
}