7

所以,我试图有这样的父/子类关系:

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;
    }
}

但是,这是一个编译错误。所以,我的第二个想法是SetParentwhere. 但问题是我不知道声明为什么类型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;
    }
}
4

1 回答 1

4

这似乎可以编译,尽管它相当费脑筋:

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;
    }
}

此解决方案使用递归绑定类型参数,它近似于“自我类型”。

我有义务链接到 Eric Lippert 关于此模式的文章:Curiouser 和好奇者

于 2013-05-31T00:30:09.770 回答