tra*_*nmq 30
除了派生之外List<T>,您还可以List<T>在Facade类中添加更多功能.
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
}
Run Code Online (Sandbox Code Playgroud)
Ant*_*lev 14
除非你有非常令人信服的理由这样做,否则你最好的选择就是继承,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>();
}
Run Code Online (Sandbox Code Playgroud)
(虽然线
readonly IList<T> _list = new List<T>();
Run Code Online (Sandbox Code Playgroud)
是最重要的!)
然后单击灯泡符号或将光标放在 IList<> 上并按Strg + "。" 您将成为提供的几种实现,例如:
| 归档时间: |
|
| 查看次数: |
36471 次 |
| 最近记录: |