以下是在System.Collections 命名空间中实现ICollection<T> 的类列表:
System.Collections.Concurrent.ConcurrentDictionary<TKey, TValue>
System.Collections.Generic.Dictionary<TKey, TValue>
System.Collections.Generic.HashSet<T>
System.Collections.Generic.LinkedList<T>
System.Collections.Generic.List<T>
System.Collections.Generic.SortedDictionary<TKey, TValue>
System.Collections.Generic.SortedList<TKey, TValue>
System.Collections.Generic.SortedSet<T>
System.Collections.ObjectModel.Collection<T>
System.Collections.ObjectModel.ReadOnlyCollection<T>
System.Collections.ObjectModel.ReadOnlyDictionary<TKey, TValue>
System.Collections.ObjectModel.WeakReadOnlyCollection<T>
但是所有这些实现都添加了额外的功能,并且由于您想从一个实现继承,但只公开ICollection<T> 方法,因此使用它们中的任何一个都不是一个真正的选择。
您唯一的选择就是实现您自己的。这很容易做到。你只需要包装一个合适的ICollection<T> 实现。这是一个默认使用List<T>,但也允许派生类使用特定类型的ICollection<T>:
class SimpleCollection<T> : ICollection<T>
{
ICollection<T> _items;
public SimpleCollection() {
// Default to using a List<T>.
_items = new List<T>();
}
protected SimpleCollection(ICollection<T> collection) {
// Let derived classes specify the exact type of ICollection<T> to wrap.
_items = collection;
}
public void Add(T item) {
_items.Add(item);
}
public void Clear() {
_items.Clear();
}
public bool Contains(T item) {
return _items.Contains(item);
}
public void CopyTo(T[] array, int arrayIndex) {
_items.CopyTo(array, arrayIndex);
}
public int Count
{
get { return _items.Count; }
}
public bool IsReadOnly
{
get { return false; }
}
public bool Remove(T item)
{
return _items.Remove(item);
}
public IEnumerator<T> GetEnumerator()
{
return _items.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return _items.GetEnumerator();
}
}
这超出了您所追求的范围,但是,例如,如果您想要存储独特的项目,您可以从中派生并提供 HashSet<T> 作为要包装的集合类型:
class UniqueCollection<T> : SimpleCollection<T>
{
public UniqueCollection() : base(new HashSet<T>()) {}
}