sách gpt4 ăn đã đi

c# - 父/子泛型关系

In lại 作者:太空狗 更新时间:2023-10-29 20:31:00 30 4
mua khóa gpt4 giày nike

所以,我正在尝试建立这样的父/子类关系:

class ParentClass where C : ChildClass
{
public void AddChild(C child)
{
child.SetParent(this); //Argument 1: cannot convert from 'ParentClass' to 'ParentClass<>,T>'
}
}
class ChildClass
{
ParentClass<>, T> myParent;
public void SetParent(ParentClass<>, T> parent)
{
myParent = parent;
}
}

但是,这是一个编译错误。因此,我的第二个想法是使用 Ở đâu tuyên bố SetParent 方法。但问题是我不知道将 myParent 声明为什么类型(我知道类型,我只是不知道如何声明它。)

class ParentClass where C : ChildClass
{
public void AddChild(C child)
{
child.SetParent(this);
}
}
class ChildClass
{
var myParent; //What should I declare this as?
public void SetParent(ParentClass parent) where K : ChildClass
{
myParent = parent;
}
}

câu trả lời hay nhất

这似乎是可以编译的,尽管它相当笨拙:

class ParentClass where C : ChildClass
{
public void AddChild(C child)
{
child.SetParent(this);
}
}
class ChildClass where C : ChildClass
{
ParentClass myParent;
public void SetParent(ParentClass parent)
{
myParent = parent;
}
}

此解决方案使用递归绑定(bind)类型参数,近似“ self 类型”。

我有义务链接到 Eric Lippert 关于此模式的文章:Curiouser and curiouser

关于c# - 父/子泛型关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16847952/

30 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress