What is the meaning of “this [int index]”?

落花浮王杯 提交于 2019-12-23 07:09:13

问题


In C# we have the following interface:

public interface IList<T> : ICollection<T>, IEnumerable<T>, IEnumerable
{
    T this [int index] { get; set; }
    int IndexOf (T item);
    void Insert (int index, T item);
    void RemoveAt (int index);
}

I don't understand the line

T this [int index] { get; set; }

What does it mean?


回答1:


That is an indexer defined on the interface. It means you can get and set the value of list[index] for any IList<T> list and int index.

Documentation: Indexers in Interfaces (C# Programming Guide)

Consider the IReadOnlyList<T> interface:

public interface IReadOnlyList<out T> : IReadOnlyCollection<T>, 
    IEnumerable<T>, IEnumerable
{
    int Count { get; }
    T this[int index] { get; }
}

And an example implementation of that interface:

public class Range : IReadOnlyList<int>
{
    public int Start { get; private set; }
    public int Count { get; private set; }
    public int this[int index]
    {
        get
        {
            if (index < 0 || index >= Count)
            {
                throw new IndexOutOfBoundsException("index");
            }
            return Start + index;
        }
    }
    public Range(int start, int count)
    {
        this.Start = start;
        this.Count = count;
    }
    public IEnumerable<int> GetEnumerator()
    {
        return Enumerable.Range(Start, Count);
    }
    ...
}

Now you could write code like this:

IReadOnlyList<int> list = new Range(5, 3);
int value = list[1]; // value = 6



回答2:


That is an indexer. So you can access the instance like an array;

See MSDN documentation.



来源:https://stackoverflow.com/questions/30511571/what-is-the-meaning-of-this-int-index

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!