Code that has the following structure:
The applyeditable of parent is a virtual method, in which the child is to perform different implementations, that is, to rewrite the Applyeditable method.
In the above code, it is clear that Parenta and PARENTB have duplicate code. However, because C # does not support multiple inheritance, it is not possible to encapsulate these duplicate codes using multiple inheritance.
We only have to take the flexible path: After my practice, use a mixed + interface approach. Can be a better implementation of multiple inheritance.
Let's take a look at the picture directly:
The specific resolution steps are:
Encapsulate the previously common code in Parenta and PARENTB into the basec and act as a property of parent.
Define the method that needs to be rewritten applyeditable in an interface ibasecaction. (In fact, if only one method needs to be rewritten, you can define an action delegate variable directly in the Basec without defining the interface.) Of course, it is easier to define interfaces to support multiple overriding methods. )
Let Childa and Childb implement the Ibasecaction interface and implement the different code for applyeditable respectively.
In the constructor of the child class, pass yourself to the instantiation of the basec, that is, this. Basec = new Basec (this);
This article supporting source code