C# 超过继承限制的组合

C# 超过继承限制的组合,c#,inheritance,design-patterns,C#,Inheritance,Design Patterns,我有许多界面,如下所示: public interface IFoo { void FooAction(); } public interface IBar { void BarAction(); } public interface IBiz { void BizAction(); } ...others... 我还为我的接口定义了一个基本抽象实现。大概是这样的: public abstract class BaseFoo() : IFoo { void

我有许多界面,如下所示:

public interface IFoo
{
    void FooAction();
}

public interface IBar
{
    void BarAction();
}

public interface IBiz
{
    void BizAction();
}

...others...
我还为我的接口定义了一个基本抽象实现。大概是这样的:

public abstract class BaseFoo() : IFoo
{
    void FooAction() { ... }
}

public abstract class BaseBar() : IBar
{
    void BarAction() { ... }
}

public abstract class BaseBiz() : IBiz
{
    void BizAction() { ... }
}

... others
现在我需要另外一些类来实现这些接口的子集。例如:

public class FooBar : IFoo, IBar
{
    ....
}

public class FooBiz : IFoo, IBiz
{
    ....
}

public class FooBarBiz : IFoo, IBar, IBiz
{
    ....
}
在支持多重继承的语言中,我将实现上述从多个抽象类继承的类:例如:

public class FooBar : BaseFoo, BaseBar, IFoo, IBar
{
    ....
}

public class FooBiz : BaseFoo, BaseBiz IFoo, IBiz
{
    ....
}

public class FooBarBiz : BaseFoo, BaseBar, BaseBiz, IFoo, IBar, IBiz
{
    ....
}
但这在C#中是不允许的,因为不支持这种继承

为了获得相同的结果,我认为这里的方法是使用组合而不是继承,并以以下方式定义类:

public class FooBar : IFoo, IBar
{
    private readonly BaseFoo Foo { get; set; } // not abstract now
    private readonly BaseBar bar { get; set; } // not abstract now

    FooBar(IFoo foo, IBar bar) // Dependency injected here
    {
        Foo = foo;
        Bar = bar;
    }

    void FooAction()
    {
        Foo.FooAction();
    }

    void BarAction()
    {
        Bar.BarAction();
    }
}
首先,这个模式正确吗? 有一件事让我觉得这里有些异味,那个就是继承之上的组合隐藏了受保护的属性和基类的字段

除了组合,我还可以为每个接口排列提供一个基本抽象类。定义BaseFooBar、BaseFooBiz、BaseFoobariz,但在这种情况下,我发现有太多的工作和重复代码


对于这类问题,哪种方法是正确的?

您正在谈论的是FooBar实现的组合。这在外部是不可见的,FooBar仍然在外部使用继承(通过接口)。为了扩展bommelding的注释,您将一些类似但不同的事情(接口实现和继承)合并在一起。组合重于继承是一个与使用接口无关的参数。接口是一个完全不同的野兽,即使它们可以用来解决类似的问题。这使得你很难对你的确切问题给出一个明确的答案,没有“一个真正的方法”。你可以对你的排列进行编码(这是已经完成的事情),但我认为实现接口的复合版本实际上相当不错。