I'm building an architecture with inheritable generics and parent-children relations.
I have one major problem: I can't make both the child and the parent aware of each other's type, only one of the two.
I need both the child and the parent to be aware of each other's type.
Scenario 1: Parent knows child type, but child only knows generic parent with generic children.
public class Child
{
public Parent<Child> Parent;
}
public class Parent<TChild>
where TChild : Child
{
public List<TChild> Children;
}
Scenario 2: Child knows parent type, but parent only knows generic children with generic parent.
public class Child<TParent>
where TParent : Parent
{
public TParent Parent;
}
public class Parent
{
public List<Child<Parent>> Children;
}
Scenario 3: The utopic but unachievable scenario:
public class Child<TParent>
where TParent : Parent
{
public TParent Parent;
}
public class Parent<TChild>
where TChild : Child
{
public List<TChild> Children;
}
Of course, scenario 3 won't compile, because Parent and Child take a second generic type that would be their own type, but I can't (or at least don't know how!) to specify it is their own type.
I'm falling in some kind of a infinite loop/recursion/ball-throw here, please help me before I drown.
Good luck.
EDIT: If I wasn't clear, I can reference my types yes, but if the user derives Child into FooChild, and accesses the children of the parent of FooChild, these will only be Child, and not FooChild, as it should be.
Failure Example with Scenario 1:
public class Child
{
public Parent<Child> Parent;
}
public class Parent<TChild>
where TChild : Child, new()
{
public List<TChild> Children;
}
public class FooChild : Child
{
public int Required;
public void Bar()
{
foreach (Child child in this.Parent.Children)
{
int x = child.Required; // cannot be accessed!
}
}
}
Failure Example with Scenario 2:
public class Child<TParent>
where TParent : Parent
{
public TParent Parent;
}
public class Parent
{
public List<Child<Parent>> Children;
}
public class FooChild : Child<Parent>
{
public int Required;
public void Bar()
{
foreach (Child<Parent> child in this.Parent.Children)
{
int x = child.Required; // cannot be accessed!
}
}
}
See Question&Answers more detail:
os