简体   繁体   English

家长/儿童仿制药关系

[英]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 . 所以,我的第二个想法是用一个where声明SetParent方法。 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.) 但问题是我不知道什么类型声明myParent (我知道类型,我只是不知道如何声明它。)

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 我有义务链接到Eric Lippert关于这种模式的文章: Curiouser和curiouser

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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