Reputation: 8315
Sorry for the bad title, but I didn't know how to entitle this in a good way.
Let the following interfaces :
interface IFoo
{
}
interface IBar
{
}
And the following classes :
class Base
{
}
class Derived1 : Base, IFoo, IBar
{
}
class Derived2 : Base, IFoo, IBar
{
}
I need to have a common type for Derived1
and Derived2
that has all the features of Base
, IFoo
and IBar
. so that i can have instances of both Derived1
and Derived2
into the same collection and have access to the features of Base
, IFoo
and IBar
without doing some reflexion black magic.
If Base
was an interface, I would just have to create an interface requiring to implement Base
, IFoo
and IBar
, but it's not the case.
I also do not want to have an intermediate inheritance between Derived1
/ Derived2
and Base
:
class Intermediate : Base, IFoo, IBar
{
}
class Derived1 : Intermediate
{
}
class Derived2 : Intermediate
{
}
Because I'm in the context of Unity and inheritance is to be avoided there more than anywhere.
Also I cannot modify Base
.
I thought about having an IBase
interface that requires all the features of Base
and have an "intermediate" interface requiring to implement it too, i.e :
interface IIntermediate : IBase, IFoo, IBar
{
}
class Derived1 : Base, IIntermediate
{
}
class Derived2 : Base, IIntermediate
{
}
But I would have to copy all of the features of Base
(and its parents) into IBase
and IBase
would also not be a Base
. So that looks a bit dirty and might cause me problems I don't see yet.
I there a different way to acheive what I need to do other than the two possibilities mentionned above ? Thank you !
Upvotes: 2
Views: 164
Reputation: 25601
How about a class with implicit operators to be able to get constructed and return all the desired types.
class MyBase : IFoo, IBar
{
Base innerValue;
public static implicit operator Base(MyBase value)
{
return value.innerValue;
}
public static implicit operator MyBase(Derived1 value)
{
return new MyBase(value);
}
public static implicit operator MyBase(Derived2 value)
{
return new MyBase(value);
}
public MyBase(Derived1 value)
{
innerValue = value;
}
public MyBase(Derived2 value)
{
innerValue = value;
}
// Implement IFoo and IBar based on innerValue calls
}
This would allow you to create an array like this:
MyBase[] myArray = new MyBase[] {new Derived1(), new Derived2()};
And you could still treat each instance as a Base:
Base B1 = myArray[0];
Upvotes: 1