实现IList接口

Ash*_*shu 12 c# generics collections ilist

我是仿制药的新手.我想通过从IList<T>接口派生它来实现我自己的集合.

能否请您提供一些实现IList<T>接口的类的链接,或者为我提供至少实现AddRemove方法的代码?

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)

  • 对于迟到的回复感到抱歉,但这个让我失去了@ IEnumerator <T> GetEnumerator`返回`GetEnumerator`.这看起来像一个循环引用.这怎么不会导致Stack Overflow异常? (2认同)

Ant*_*lev 14

除非你有非常令人信服的理由这样做,否则你最好的选择就是继承,System.Collections.ObjectModel.Collection<T>因为它拥有你需要的一切.

请注意,虽然实现IList<T>者不需要实现this[int](索引器)为O(1)(基本上是恒定时间访问),但强烈建议您这样做.


mar*_*gle 9

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 + "。" 您将成为提供的几种实现,例如:

在此处输入图片说明

  • 正是我所需要的。应该被接受的答案,因为这是正确的方法。 (4认同)