0

私は理解しようとしているこのクラスを持っています:

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 を使用するのはなぜですか? base.InsertItem とその他 (アイテムの設定、削除、クリア) を省略しても問題ありません。


私は私の質問について十分に明確ではなかったと思います。

私の意見では、 base.InsertItem コレクションにアイテムを追加するのは Collections メソッドです。すでに追加しているのであれば、なぜこれを item.Album に割り当てているのでしょうか。

Track クラスにある Album と Collection を使用している Album クラスについて少し混乱しています。

このコレクションの使用例を誰かに見せてもらえますか?
ありがとう!

4

2 に答える 2

0

このメソッドのオーバーライドがあります:

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

これにより、基本クラスから継承されたメソッドの動作がInsertItemCollection<Track>変更されます。最初の行は、基本クラスから実装を呼び出します。その後、基本クラスと同じことを行いました。2 行目は、現在のコレクション ( 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、 を に書き込むことAlbumですitem。基になるコレクションには実際には何も挿入されません。これはおそらくあなたが望むものではありません。


So what is the base keyword for? It allows you to call the method (or other member) of the base class even if the method was overridden of hidden on the current class. Your example gives the typical use of the base access.

于 2013-10-09T08:39:46.000 に答える