"this [int index]"的含义

bor*_*ris 11 .net c# interface

在C#中我们有以下界面:

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);
}
Run Code Online (Sandbox Code Playgroud)

我不明白这条线

T this [int index] { get; set; }
Run Code Online (Sandbox Code Playgroud)

这是什么意思 ?

Ham*_*ein 14

那是一个索引器.所以你可以像数组一样访问实例;

https://msdn.microsoft.com/en-us/library/6x16t2tx.aspx


Tim*_*lds 10

这是在接口上定义的索引器.这意味着你可以get和任何和set的价值.list[index]IList<T> listint index

文档:接口中的索引器(C#编程指南)

考虑IReadOnlyList<T>界面:

public interface IReadOnlyList<out T> : IReadOnlyCollection<T>, 
    IEnumerable<T>, IEnumerable
{
    int Count { get; }
    T this[int index] { get; }
}
Run Code Online (Sandbox Code Playgroud)

以及该接口的示例实现:

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);
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)

现在您可以编写如下代码:

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