简体   繁体   中英

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.

My problem now is, that SpecificY doesn't have the property C from SpecificX , because I cannot do multiple inheritance like

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. And as soon as C is becoming more than a simple Property, things get ugly. 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. 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; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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