C#中的通用列表类

5

我目前正在制作自己的基本 通用列表类(以更好地了解预定义的类的工作方式)。 我唯一遇到的问题是,我无法像在使用“System.Collections.Generic.List”时那样访问数组内部的元素。

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

这很好,但当尝试访问“whatever”时,我想能够编写
list[0];

但显然这并不起作用,因为在代码中我明显缺少了什么,我需要添加什么来完善我的通用类呢?


你的GenericList类是什么样子的? - LukeHennerley
顺便提一下,在通用列表中有一个有用的功能是像 public void ActOnElement<TP1>(int index, ActByRef<T,TP1> proc, ref TP1 param1) { proc(ref Array[index], ref TP param1); } 这样的方法,它将允许代码直接对列表项进行操作 [假设 public delegate void ActByRef<T1,T2>(ref T1 p1, ref T2 p2);]。如果有一个 GenericList<Rectangle>,这样的方法可以让代码说 myList.ActOnItem(index, (ref Rectangle r, ref int v) => {r.X -= v; r.Width+=v;}, ref widthAdjust) 来更新一个列表项“就地”。 - supercat
2个回答

12

它被称为索引器,写作如下:

public T this[int i]
{
    get
    {
        return array[i];
    }
    set
    {
        array[i] = value;
    }
}

我怀疑 OP 的意思是当访问 GenericList 实例时,他得到了“只有赋值、调用、递增、递减和新对象表达式可以用作语句”的错误信息?显然,如果他甚至无法访问索引,那么你的答案就没问题 :) - LukeHennerley
@LukeHennerley 我相信 OP 是在寻找在他们的 GenericList 类型中放置属性声明,以便:给定一个 GenericList list 实例,他们可以使用索引器访问其中的元素,例如 list[0] - Rich O'Kelly
我也有这样的怀疑,只是在想 OP 可能会被误解。无论如何,+1 :) - LukeHennerley

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; }
  }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接