我对泛型不熟悉。我想通过继承 IList<T>
接口来实现自己的集合。
请您提供一个实现了 IList<T>
接口的类的链接,或者提供一个至少实现了 Add
和 Remove
方法的代码吗?
我对泛型不熟悉。我想通过继承 IList<T>
接口来实现自己的集合。
请您提供一个实现了 IList<T>
接口的类的链接,或者提供一个至少实现了 Add
和 Remove
方法的代码吗?
List<T>
,您还可以使用外观模式List<T>
并向您的外观类添加更多功能。class MyCollection<T> : IList<T>
{
private readonly IList<T> _list = new List<T>();
#region Implementation of IEnumerable
public IEnumerator<T> GetEnumerator()
{
return _list.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
#region Implementation of ICollection<T>
public void Add(T item)
{
_list.Add(item);
}
public void Clear()
{
_list.Clear();
}
public bool Contains(T item)
{
return _list.Contains(item);
}
public void CopyTo(T[] array, int arrayIndex)
{
_list.CopyTo(array, arrayIndex);
}
public bool Remove(T item)
{
return _list.Remove(item);
}
public int Count
{
get { return _list.Count; }
}
public bool IsReadOnly
{
get { return _list.IsReadOnly; }
}
#endregion
#region Implementation of IList<T>
public int IndexOf(T item)
{
return _list.IndexOf(item);
}
public void Insert(int index, T item)
{
_list.Insert(index, item);
}
public void RemoveAt(int index)
{
_list.RemoveAt(index);
}
public T this[int index]
{
get { return _list[index]; }
set { _list[index] = value; }
}
#endregion
#region Your Added Stuff
// Add new features to your collection.
#endregion
}
除非你有非常充分的理由需要这样做,否则最好从System.Collections.ObjectModel.Collection<T>
继承,因为它拥有你所需的一切。
请注意,虽然实现IList<T>
的人不需要将this[int]
(索引器)实现为O(1)(基本上是常数时间访问),但强烈建议你这样做。
public class MyCollection<T> : IList<T>
{
// This line is important. Without it the auto implementation creates only
// methods with "NotImplemented" exceptions
readonly IList<T> _list = new List<T>();
}
(当行
readonly IList<T> _list = new List<T>();
是重要的部分!
然后点击灯泡符号或者将光标放在IList<>上并按下Strg + "." ,会弹出几个可用的实现,例如:
List<T>
或从 List<T>
派生。 如果您从 List<T>
派生,则会自动获得 Add 和 Remove 的实现。
IEnumerator<T> GetEnumerator
返回GetEnumerator
的部分让我有些困惑。这看起来像是一个循环引用。为什么不会导致堆栈溢出异常呢? - user153923