Deriving from List<T>
is somewhat pointless, especially now that it has the IEnumerable<T>
constructor and the availability of extension methods. It has no virtual methods that you can override except Equals
, GetHashCode
, and ToString
. (I suppose you could derive from List<T>
if your goal was to implement Java's toString() functionality for lists.)
If you want to create your own strongly-typed collection class and possibly customize the collection behavior when items are add/removed, you want to derive from the new (to .NET 2.0) type System.Collections.ObjectModel.Collection<T>
, which has protected virtual methods including InsertItem
and RemoveItem
that you can override to perform actions at those times. Be sure to read the documentation - this is a very easy class to derive from but you have to realize the difference between the public/non-virtual and protected/virtual methods. :)
public class MyCollection : Collection<int>
{
public MyCollection()
{
}
public MyCollection(IList<int> list)
: base(list)
{
}
protected override void ClearItems()
{
// TODO: validate here if necessary
bool canClearItems = ...;
if (!canClearItems)
throw new InvalidOperationException("The collection cannot be cleared while _____.");
base.ClearItems();
}
protected override void RemoveItem(int index)
{
// TODO: validate here if necessary
bool canRemoveItem = ...;
if (!canRemoveItem)
throw new InvalidOperationException("The item cannot be removed while _____.");
base.RemoveItem(index);
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…