Abstract with heir as a field

I am making a program with several types of binary trees. So I decided to make an abstract class to avoid copying the code. But the problem is that the nodes of each tree must contain children of the same type as the node itself. Is there any means to define this in the abstract, or should I just create different classes for each type at the end?

public abstract class BinaryNodeAbstract<T> { public T Value; public BinaryNodeAbstract<T> Left; public BinaryNodeAbstract<T> Right; 

As now, nodes can be any type of BinaryNode. This should be avoided.

+5
source share
1 answer

You must also include the parent type to save the inherited type to Left and Right (otherwise you cannot use the inherited type in the implementation):

 public abstract class BinaryNodeAbstract<T, L> where L : BinaryNodeAbstract<T, L> { public T Value; public L Left; public L Right; } 

You can use it as follows:

 public class BinaryNodeImplementation : BinaryNodeAbstract<int, BinaryNodeImplementation> { } 
+7
source

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


All Articles