簡體   English   中英

當該子項作為其父項存儲在列表中時,如何訪問Child類的接口屬性?

[英]How can I access a Child class's interface property when that child is stored in a list as its Parent?

我認為這篇文章的標題可能無法很好地解釋我的問題,所以這里有一些代碼應該希望能更好地解釋一下:

interface IFoo {
    IFoo Bar {get; set;}
}

class Parent {

}

class Child1 : Parent, IFoo {

}

class Child2 : Parent, IFoo {

}

class Manager {
    List<Parent> Parents = new List<Parent>();

    Parents.Add(new Child1());
    Parents.Add(new Child2());

    // I want to do something like this:
    Parents[0].Bar = Parents[1];
}

我相信(Parents[0] is IFoo)將評估為true ,但我不能使用Parents[0].Bar因為Parent不包含Bar的定義。 你能解釋一下這是為什么嗎? 另外,我怎么能有效地做同樣的事情(至少在我腦海里) Parents[0].Bar = Parents[1]應該做什么?

希望這是有道理的。 如果需要,我會盡力澄清事情。 在此先感謝您的光臨!

使用類型轉換:

((IFoo)Parents[0]).Bar

但實際上,如果你依賴於實體,那么你的設計就是糟糕的設計。

如果要進行分配,則需要讓代碼具有與自己相同的信息,以及與Manager類相同的信息。 這意味着你必須告訴類Parent它知道IFoo,這意味着:

 abstract class Parent : IFoo
{
    public abstract IFoo Bar { get; set; }
}

它現在還聲明您無法單獨實例化Parent。 從您的評論中,它似乎有意義(您說父母應該沒有Bar的實現,只知道它)。 如果這是有意義的,那么它是抽象的,但如果不刪除摘要並將Bar的實現添加到Parent,或者如果每個子項的實際實現不同,則將其設置為虛擬。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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