简体   繁体   中英

Parent/Child Generics Relationship

So, I'm trying to have a parent/child class relationship like this:

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 compile error. So, my second thought was to declare the SetParent method with a where . But the problem is that I don't know what type declare myParent as (I know the type, I just son'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;
    }
}

This seems to compile, though it's rather hairbrained:

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 makes use of a recursively bound type parameter, which approximates the "self-type".

I'm obligated to link to Eric Lippert's article on this pattern: Curiouser and curiouser

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM