Is it possible to define a "generic" method for C # interfaces?
Let's say I have 4 classes: Foo
, Bar
, Qux
and Baz
. I also have an interface IFubar
.
Classes inherit from each other like this:
Bar : Foo, IFubar
Qux : Baz, IFubar
The methods in will IFubar
almost always be implemented the same way, no matter which class inherits them. The ideal solution would be to implement the implementation in IFubar
, but I cannot change IFubar
to a class because Bar
both Qux
must inherit from Foo
and Baz
accordingly, and C # does not support multiple inheritance.
Is there an easy way to have some kind of "standard" logic in the interface, for lack of a better term? Right now, my "implementation" is just a call to a static method in another class that allows me to execute all my logic and minimize code duplication. However, I feel that this is not an elegant solution.
Ideally, I would like to get a class from some class and IFubar
and automatically get the same implementation IFubar
without having to copy and paste. I'm sure this is not possible with C #, but I want to make sure.
To be honest, this is nothing more than a mild annoyance that I have to copy and paste the same code over and over, but I am trying to think of a more elegant solution and I cannot.
This will all be for something used in the Unity3D engine, so I'll mostly limit myself to .NET 3.5.
Does anyone have any better solutions or suggestions?
source to share
"Almost always" is a problem. If it were "always", then the "extension method" would be ideal:
public static class FubarExtensions
{
public static void SomeMethod(this IFubar obj) { ... }
}
If you want "almost" you probably need polymorphism to be reliable. In this case, using a static method for the default implementation is probably your best option, i.e.
IFubar.SomeMethod(...)
{
Fubar.SomeMethodDefault(this, ...);
}
or
public virtual void SomeMethod(...)
{
Fubar.SomeMethodDefault(this, ...);
}
(or any similar combination)
source to share
If the implementation is always the same, you can use something like this:
class Fubar : IFubar {
public void SomeIFubarMethod() { β¦ }
}
class Foo : Fubar { β¦ }
class Baz : Fubar { β¦ }
Then you can use the same inheritance for Bar
and Qux
(and you don't even need to specify the interface again IFubar
):
class Bar : Foo { β¦ }
class Qux : Baz { β¦ }
source to share