簡體   English   中英

家長/兒童仿制葯關系

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM