【发布时间】:2010-11-13 16:02:09
【问题描述】:
我是泛型新手。我想通过从IList<T> 接口派生来实现我自己的集合。
您能否提供一些指向实现IList<T> 接口的类的链接,或者提供至少实现Add 和Remove 方法的代码?
【问题讨论】:
标签: c# generics collections ilist
我是泛型新手。我想通过从IList<T> 接口派生来实现我自己的集合。
您能否提供一些指向实现IList<T> 接口的类的链接,或者提供至少实现Add 和Remove 方法的代码?
【问题讨论】:
标签: c# generics collections ilist
除了从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
}
【讨论】:
IEnumerator<T> GetEnumerator,返回GetEnumerator。这看起来像一个循环引用。这怎么不会导致堆栈溢出异常?
除非您有非常令人信服的理由这样做,否则最好的选择是从 System.Collections.ObjectModel.Collection<T> 继承,因为它拥有您需要的一切。
请注意,尽管 IList<T> 的实现者不需要将 this[int](索引器)实现为 O(1)(基本上是恒定时间访问),但强烈建议您这样做。
【讨论】:
Visual Studio 提供了一个自动完整的工作实现接口,如 IList。
你只需要编写类似这样的代码:
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 +“。”您将成为提供的几种实现方式,例如: p>
【讨论】:
您可以查看Mono project。有可用的完整源代码,你可以看看一些类是如何实现的。例如“System.Collections.Generics.List
【讨论】:
在大多数情况下,您可以简单地使用List<T> 或从List<T> 派生。如果您从 List<T> 派生,您将自动获得 Add 和 Remove 的实现。
【讨论】:
从 List 继承通常是最快的方法,但如果您需要从另一个类(例如 ContextBoundObject 等)继承,以后可能会受到限制。实现 IList 非常快,并且如上所述,它提供了更多的灵活性。
【讨论】: