“this [int index]”的意思是什么?

13

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

我不理解这行代码

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

这是什么意思?


1
这意味着如果你调用 myList[myInteger] = foo; 或者 T foo = myList[myInteger],你会得到一个额外的方法 get_Itemset_Item 来处理内部操作,其中 foo 的类型为 T - atlaste
2个回答

14

13

这是在接口上定义的索引器。这意味着您可以为任何 IList<T> listint index 获取和设置 list[index] 的值。

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

考虑 IReadOnlyList<T> 接口:

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

下面是一个关于该接口的示例实现:

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

现在你可以编写如下代码:
IReadOnlyList<int> list = new Range(5, 3);
int value = list[1]; // value = 6

你能告诉我这个程序何时有用吗? - Kaushik Thanki

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