2015-05-28 14 views
8

W języku C# mamy następujący interfejs:Sens "o [int index]"

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

Nie rozumiem linię

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

Co to znaczy?

+0

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

Odpowiedz

9

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 
+0

czy możesz mi powiedzieć, kiedy ta taksówka będzie pomocna –