There is a hierarchy of classes, there is a situation in which I can not come up with a normal solution. (arrows show inheritance, red color - desired, but impossible)

enter image description here

Classes U , S , A , W use the same implementation of function F

And the classes SAI , AAI , WAI are different, but common to each other. This is precisely what cannot be realized as there is no possibility to create an additional class AI to implement F in it and then inherit from it. It turns out that you just have to copy the F implementation for SAI , AAI , WAI , which is bad.

What is a beautiful way to solve this problem ??

Thank!

  • one
    to put the function F in a separate class and throw it through DI? - Zufir
  • 3
    maybe some kind of strategy will do - Grundy
  • AI can not stick between U and S, A, W? Then it would be quite what you need. - Monk
  • @Monk, no F is implemented in U, SAW - just add-ins over U that need to be transferred to SAW AI. but at the same time override the implementation of F, and there will be other add-ins (common) for SAW AI, which is also problematic. Probably have to change the structure of the code ... - Valera Kvip

2 answers 2

Multiple inheritance from multiple classes is not possible. Use the interface IFunctionF and two auxiliary classes F1 and F2 , each of which has its own implementation IFunctionF . And further from F1 and F2 inherit your families U,A,S,W from F1 and SAI, AAI, WAI from F2 .

  public interface F { int F(); } class F1:F { public virtual int F() { return 2; } } class F2 : F { public virtual int F() { return 3; } } class S : F1 { void a() { F(); } } class AAI : F2 { void a() { F(); } } 
  • This is what I am trying to solve. I do not want to copy 100,500 times the same implementation - Valera Kvip
  • But then it will not be possible to realize inheritance as in the picture in question. - Valera Kvip

C # Extension methods may help you with code reuse (but not a fact, since you cannot use private members of classes).

Example:

 Interface IFoo {} public static class IFooExtensions { public static int F(this IFoo foo) { //.... } } //........... int value = (myObj as IFoo).F();