简体   繁体   English

如何从抽象基类多重继承?

[英]How to mulitiply inherit from abstract base classes?

I have some abstract base classes to be used on multiple implementations.我有一些抽象基类可用于多个实现。

Base classes:基类:

public abstract class BaseX
{
    public string A { get; set; }
}

public abstract class BaseY : BaseX
{
    public string B { get; set; }
}

For each use case, I want to create from these base classes specific classes like:对于每个用例,我想从这些基类创建特定类,例如:

public abstract SpecificX : BaseX
{
    public string C { get; set; }
}

public abstract SpecificY : BaseY
{
    public string D { get; set; }
}

All classes that derive from SpecificY should contain all the properties A, B, C, D.SpecificY派生的所有类都应包含所有属性A、B、C、D。

My problem now is, that SpecificY doesn't have the property C from SpecificX , because I cannot do multiple inheritance like我现在的问题是, SpecificY没有来自SpecificX的属性 C,因为我不能像这样进行多重继承

public abstract SpecificY : BaseY, SpecificX

My only idea would be to use Interface like this:我唯一的想法是使用这样的接口:

public Interface ISpecificX
{
    string C { get; set; }
}

public abstract SpecificX : BaseX, ISpecificX
{
    public string C { get; set; }
}

public abstract SpecificY : BaseY, ISpecificY
{
    public string D { get; set; }
    public string C { get; set; } <== redundancy
}

But then I'd need to implement C twice.但是我需要实现 C 两次。 And as soon as C is becoming more than a simple Property, things get ugly.一旦 C 变得不仅仅是一个简单的属性,事情就会变得丑陋。 Is there a better way to create this structure?有没有更好的方法来创建这种结构?

Thanks in advance,提前致谢,
Frank坦率

I would strongly suggest to favour composition over inhertiance - as propsed by the GoF.我强烈建议支持组合而不是继承- 正如 GoF 所支持的那样。 This way you do not inherit a given class, but just use an instance of it.这样你就不会继承给定的类,而只是使用它的一个实例。 Then you can easily have all your properties without any duplication:然后,您可以轻松拥有所有属性而无需任何重复:

class BaseX { ... }
class BaseY { ... }

class SpecificY : BaseY
{
    private readonly SpecificX b = new SpecificX();
    public string A { get => this.b.A; set => this.b.A = value; } // delegate the call
    public string B { get; set; }
    public string C { get => this.b.C; set => this.b.C = value; } // delegate the call
    public string D { get; set; }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM