5

我目前正在制作自己的非常基本的通用列表类(以便更好地了解预定义的列表类是如何工作的)。我唯一的问题是我无法像您通常使用“ System.Collections.Generic.List”所说的那样到达数组内的元素。

GenericList<type> list = new GenericList<type>();
list.Add(whatever);

这很好用,但是当尝试访问我希望能够编写的“任何内容”时

list[0];

但这显然是行不通的,因为我显然在代码中遗漏了一些东西,我需要将什么添加到我原本完全正常工作的泛型类中?

4

2 回答 2

12

它被称为indexer,写法如下:

public T this[int i]
{
    get
    {
        return array[i];
    }
    set
    {
        array[i] = value;
    }
}
于 2013-02-19T16:25:49.467 回答
1

我认为您需要做的就是实现IList<T>,以获得所有基本功能

  public interface IList<T>  
  {

    int IndexOf(T item);

    void Insert(int index, T item);

    void RemoveAt(int index);

    T this[int index] { get; set; }
  }
于 2013-02-19T17:04:04.473 回答