Is there something like a class that can be implemented?

I would like to write a class X (this) that inherits from A (the base) can
execute methods B (?) and must implement elements of C (interface).

Implementing A and C is not a problem. But since X cannot be deduced from several classes, it seems that X does not inherit the logic of A and B. Note that A is a very important base class, and B is almost an interface, but contains executable behavior. The reason I don't want B to be an interface is because the behavior is the same for every class that inherits or implements it.

Do I really have to declare B as an interface and implement the same 10 lines of code for each X that requires the behavior of B?


2 months later
I am currently studying C ++ for use in UE4 (Unreal Engine 4).
Since C ++ is much less strict than C #, it actually contains the term pattern idom implementation that describes this behavior: they are called mixin s.

You can read the paragraph on C ++ mixing here on page 9 (second paragraph).

+6
source share
2 answers

Do I really have to declare B as an interface and implement the same 10 lines of code for every X that needs the behavior of B ?

Yes and no. You need to do B interface. But common method implementations should not be duplicated in all interface implementations. Instead, they should go into a class extension for interface B :

 public interface B { void MethodX(); void MethodY(); } public static class ExtensionsB { public static void MethodZ(this B b) { // Common implementations go here } } 

Extension methods provide a way to share horizontal implementations without your classes inheriting from the second class. Extension methods behave as if they were ordinary class methods:

 class X : A, B { public void MethodX() {...} public void MethodY() {...} } public static void Main(string[] args) { var x = new X(); x.SomeMethodFromA(); x.MethodX(); // Calls method from X x.MethodY(); // Calls method from X x.MethodZ(); // Calls method from ExtensionsB } 
+5
source

I think that it would be best to require an instance of B in constructor A , and then set or call methods B as necessary:

 public class X : A, C { private readonly B _b; public X(B b) { _b = b; } } 

You will find a lot of information about this kind of approach if you look at Composition over inheritance

+1
source

Source: https://habr.com/ru/post/985581/


All Articles