To jest indekser zdefiniowane w interfejsie. Oznacza to, że możesz get
i set
o wartości list[index]
dla dowolnego IList<T> list
i int index
.
Dokumentacja: Indexers in Interfaces (C# Programming Guide)
Rozważmy interfejs IReadOnlyList<T>
:
public interface IReadOnlyList<out T> : IReadOnlyCollection<T>,
IEnumerable<T>, IEnumerable
{
int Count { get; }
T this[int index] { get; }
}
a przykładem realizacji tego interfejsu:
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);
}
...
}
Teraz można napisać kod tak:
IReadOnlyList<int> list = new Range(5, 3);
int value = list[1]; // value = 6
Oznacza to, że otrzymujesz dodatkową metodę 'get_Item' i' set_Item', która wykonuje wewnętrzne operacje, jeśli wywołasz 'myList [myInteger] = foo;' lub 'T foo = myList [myInteger]' gdzie 'foo' jest typu 'T'. – atlaste