Parent relationship

So, I am trying to establish the parent / child class relationship as follows:

class ParentClass<C, T> where C : ChildClass<T> { public void AddChild(C child) { child.SetParent(this); //Argument 1: cannot convert from 'ParentClass<C,T>' to 'ParentClass<ChildClass<T>,T>' } } class ChildClass<T> { ParentClass<ChildClass<T>, T> myParent; public void SetParent(ParentClass<ChildClass<T>, T> parent) { myParent = parent; } } 

But this is a compilation error. So my second thought was to declare the SetParent method with where . But the problem is that I don’t know what type declares myParent as (I know the type, I just don’t know how to declare it.)

 class ParentClass<C, T> where C : ChildClass<T> { public void AddChild(C child) { child.SetParent(this); } } class ChildClass<T> { var myParent; //What should I declare this as? public void SetParent<K>(ParentClass<K,T> parent) where K : ChildClass<T> { myParent = parent; } } 
+6
source share
1 answer

This is similar to compilation, although it is more related to hair:

 class ParentClass<C, T> where C : ChildClass<C, T> { public void AddChild(C child) { child.SetParent(this); } } class ChildClass<C, T> where C : ChildClass<C, T> { ParentClass<C, T> myParent; public void SetParent(ParentClass<C, T> parent) { myParent = parent; } } 

This solution uses a recursively related type parameter that approximates the "type itself."

I must link Eric Lippert's article with this template: Curious and Curious

+3
source

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


All Articles