I have the following base interface
public interface IBaseAction
{
bool CanAct(...)
}
and two inheriting interface say
public interface IAction1 : IBaseAction{}
and
public interface IAction2 : IBaseAction{}
My problem is, I have a class which implements both, and I want to implement CanAct DIFFERENTLY.
public class ComplexAction : IAction1, IAction2
{
bool IAction1.CanAct(...){} //doesn't compile as CanAct is not a member of IAction1!!
}
ComplexAction c=new ComplexAction();
var a1 = (IAction1)c;
var a2 = (IAction2)c;
a1.CanSave(); //THESE TWO CALLS SHOULD BE IMPLEMENTED DIFFERENTLY
a2.CanSave();
Is there a reasonably clean way to do this?
(Also, my interfaces have semantic meaning and at least three more functions, so it is out of the question to throw out the whole hierarchy, but I'd be willing to copy bool CanAct to every inheriting interface if that is the only solution (there are 4-6 of them))
A class can implement multiple interfaces and many classes can implement the same interface. A class can implement multiple interfaces and many classes can implement the same interface.
An interface can extend any number of interfaces but one interface cannot implement another interface, because if any interface is implemented then its methods must be defined and interface never has the definition of any method.
C# allows the implementation of multiple interfaces with the same method name.
Interfaces can inherit from one or more interfaces. The derived interface inherits the members from its base interfaces. A class that implements a derived interface must implement all members in the derived interface, including all members of the derived interface's base interfaces.
And what the CLR is supposed to do if someone calls ((IBaseAction)a1).CanSave()
? There could be just one implementation for IBaseAction.CanSave()
. So I think you can't do this conceptually.
This is a fundamental problem of multiple inheritance called the diamond problem. The bottom line is: if you hit it, your type hierarchy design is definitely wrong. E.g. in this particular case, you're better off with the Role class model (also known as the Role pattern).
You can't do what you describe. Just imagine what would happen if a client requests the IBaseAction
interface. Which one should be returned?
It sounds to me like each action should be implemented by separate objects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With