简体   繁体   English

c#中的泛型列表类

[英]generic list class in c#

I'm currently making my own very basic generic list class (to get a better understanding on how the predefined ones work). 我目前正在制作我自己的非常基本的通用列表类 (以便更好地理解预定义的列表类如何工作)。 Only problem I have is that I can't reach the elements inside the array as you normally do in say using " System.Collections.Generic.List ". 我遇到的唯一问题是我无法像通常使用“ System.Collections.Generic.List ”那样访问数组中的元素。

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

This works fine, but when trying to access "whatever" I want to be able to write : 这工作正常,但在尝试访问我希望能够编写的“任何”时

list[0];

But that obviously doesn't work since I'm clearly missing something in the code, what is it I need to add to my otherwise fully working generic class ? 但这显然不起作用,因为我在代码中明显遗漏了一些内容,我需要添加到我完全正常工作的泛型类中的是什么?

It's called an indexer , written like so: 它被称为索引器 ,如下所示:

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

I think all you need to do is implement IList<T> , to get all the basic functionality 我认为您需要做的就是实现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; }
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM