Geyearchical nested common interfaces

I have a chain of hierarchically nested generic interfaces that looks like this for example:

ICar<TWheels, TBolts>
where TWheels : IWheels<TBolts>
where TBolts : IBolts
{
    IEnumerable<TWheels> Wheels { get; set; }
}

IWheels<TBolts>
where TBolts : IBolts
{
    IEnumerable<TBolts> Wheels { get; set; }
}

IBolts
{

}

      

Is this a sane way to handle these common interfaces?

It makes the definition methods like this:

public TCar GetCar<TWheels, TBolts>(int id)
where TCar : ICar<TWheels, TBolts>
where TWheels : IWheels<TBolts>
where TBolts : IBolts
{
    ...
}

      

Is there a way to reduce this code signature?

+3


source to share


1 answer


Generics in C # should be used very carefully to avoid the problems you are experiencing. I would recommend revisiting the interface hierarchy and throwing out generics:

interface ICar
{
    IEnumerable<IWheel> Wheels { get; set; }
}

interface IWheel
{
    IEnumerable<IBolt> Bolts { get; set; }
}

interface IBolt
{
}

      

Then it would be great to look at the use cases that these interfaces are involved in.
Maybe there will be very rare cases where you will need IR16Wheel

instead IWheel

and type casting will suffice.
Maybe this is enough to connect non-common interfaces with common ones:

interface IWheel<TBolt> : IWheel
    where TBolt : IBolt
{
    IEnumerable<TBolt> Bolts { get; set; }
}

      



and use non-generics with methods like this:

public ICar GetCar(int id) { }

      

but also use generics in more specific cases.

+1


source







All Articles