[英]Parent/Child Generics Relationship
所以,我正在尝试这样的父/子类关系:
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;
}
}
但是,这是一个编译错误。 所以,我的第二个想法是用一个where
声明SetParent
方法。 但问题是我不知道什么类型声明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;
}
}
这似乎是编译,虽然它是相当头发的:
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和curiouser
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.