17

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

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

4

6 回答 6

35

除了派生自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
}
于 2009-07-24T08:59:51.990 回答
15

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

请注意,尽管 的实现IList<T>者不需要将this[int](indexer) 实现为 O(1)(基本上是恒定时间访问),但强烈建议您这样做。

于 2009-07-24T08:43:24.503 回答
11

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

在此处输入图像描述

于 2019-08-14T11:03:13.547 回答
1

你可以看看Mono 项目。有可用的完整源代码,你可以看看一些类是如何实现的。例如“System.Collections.Generics.List<T>”。

于 2009-07-24T08:36:51.630 回答
1

在大多数情况下,您可以简单地使用List<T>或派生自List<T>. 如果您从中派生,List<T>您将自动获得 Add 和 Remove 的实现。

于 2009-07-24T08:39:28.783 回答
0

从 List 继承通常是最快的方法,但如果您需要从另一个类(例如 ContextBoundObject 等)继承,以后可能会受到限制。实现 IList 非常快,并且如上所述,它提供了更多的灵活性。

于 2011-02-04T10:08:49.147 回答