2013-10-09 29 views
0

我有這個類,我想了解:System.Collections.ObjectModel收集<T>

public class Track 
{ 
    public string Title { get; set; } 
    public uint Length { get; set; } 
    public Album Album { get; internal set; } 
} 

public class Album : Collection<Track> 
{ 
    protected override void InsertItem(int index, Track item) 
    { 
     base.InsertItem(index, item); 
     item.Album = this; 
    } 

protected override void SetItem(int index, Track item) 
{ 
    base.SetItem(index, item); 
    item.Album = this; 
} 

protected override void RemoveItem(int index) 
{ 
    this[index].Album = null; 
    base.RemoveItem(index); 
} 

protected override void ClearItems() 
{ 
    foreach (Track track in this) 
    { 
     track.Album = null; 
    } 
    base.ClearItems(); 
} 
} 

爲什麼我們使用base.InsertItem,而分配 新變量之後,會不會是OK省略基地.InsertItem和其他 (設置,刪除,清除項目)。


我想我對於我的問題還不夠清楚。

base.InsertItem在我看來,它是集合方法 將項目添加到集合。所以,如果我們已經添加了 ,我們將其分配給item.Album。

我對使用Collection的Track 類和Album類有點迷惑。

有人可以告訴我使用這個集合的例子嗎?
謝謝!

回答

0

你有這樣的方法覆蓋:

protected override void InsertItem(int index, Track item) 
{ 
    base.InsertItem(index, item); 
    item.Album = this; 
} 

這改變了從基類繼承Collection<Track>the behavior of the InsertItem method。第一行調用基類的實現。所以在那之後,我們做了和基類一樣的工作。第二行通過提供對當前集合的引用來修改要插入的項目(Album)。

目前還不清楚你問什麼,但假設你這樣做,而不是:

protected override void InsertItem(int index, Track item) 
{ 
    InsertItem(index, item); // bad 
    item.Album = this; 
} 

這不會是一個好主意,因爲現在的方法遞歸調用自己循環往復。所以這不是一個選項。

假設你做,而不是這樣的:

protected override void InsertItem(int index, Track item) 
{ 
    item.Album = this; 
} 

現在,只有東西InsertItem方法確實是寫Albumitem。底層集合中沒有插入任何內容。這可能不是你想要的。


那麼什麼是base關鍵字?它允許您調用基類的方法(或其他成員),即使方法被當前類的隱藏重寫。你的例子給出了base訪問的典型用法。

1

爲什麼我們使用base.InsertItem,而在分配新變量之後?

Track是一個class,所以它有引用類型的語義。這意味着,只要 - 它並不重要,因爲它存在於託管堆中,而其他所有內容都只是對它的引用,您可以在之前,之後分配其Album屬性。

你出什麼是常見的成語 - 您添加TrackAlbum(這是一個TracksCollection),然後設置一個「回參考」:您設置的TrackAlbum屬性爲您剛剛添加到的Album

請注意,他們在之後執行之後的任務InsertItem被調用,因爲這是正確的事件順序。該項目在添加之前不屬於該集合的一部分。另請注意,RemoveItem覆蓋以相反的順序進行。

可以省略base.InsertItem和其他(設置,刪除,清除項目)。

你告訴我 - 這取決於你打算如何使用代碼。您所展示的是一個簡單的強類型集合,它管理添加到該集合的項目的「容器引用」。例如,在整個Windows.Forms代碼中,這是一種常見的格式。

+0

我會說在'base'調用中離開,因爲你希望運行默認的收集方法。他現在唯一可以改變的地方就是刪除後面的引用,並在整個代碼中執行這些引用(這個例子試圖簡化)。除非你開發一種你想要實現的不同的技術方法,否則我會說它保持原樣。直到你理解當前代碼的作用和原因,你才能做到這一點。 – ps2goat

+0

@ ps2goat我會調用'base'調用必不可少的 - 刪除它們並且集合什麼也不會存儲(除非你刪除覆蓋當然)。 –

+0

@Johnathon Reinhart,我知道你會的。我只是添加評論來讓海報思考。 – ps2goat