English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Indiceador (Indexer) do C#

Um indexador é um tipo especial de propriedade que permite acessar uma classe ou estrutura como se fosse um array interno. O C# nos permite definir indexadores personalizados, indexadores genéricos e indexadores sobrecarregados.

Você pode definir um indexador usando uma propriedade com a palavra-chave this e colchetes [].

Sintaxe

<return type> this[<parameter type> index]
{ 
   get {
        // Retornar valor do índice específico do conjunto interno
    }
   set { 
       // Definir valor no índice específico do conjunto interno
    }
}

Definição de indexador

A seguir, um exemplo define um indexador dentro de uma classe.

class StringDataStore
{
    private string[] strArr = new string[10; // 内部数据存储
    public string this[int index]
    {
        get
        {
            if(index < 0 || index >= strArr.Length)
                throw new IndexOutOfRangeException("Index out of range");
                return strArr[index];
        }
        set
        {
            if (index < 0 || index >= strArr.Length)
                throw new IndexOutOfRangeException("Index out of range");
            strArr[index] = value;
        }
    }
}

A classe StringDataStore define um indexador para o array privado strArr. Agora, você pode usar StringDataStore para adicionar e recuperar valores de strings do strArr, conforme mostrado a seguir.

StringDataStore strStore = new StringDataStore();
strStore[0] = "One";
strStore[1] = "Two";
strStore[2] = "Three";
strStore[3] = "Four";
        
for (int i = 0; 10 ; i++)
    Console.WriteLine(strStore[i]);
Saída:
One
Two
Three
Four

De C# 7A partir de agora, você pode usar a sintaxe de expressão corpo para get e set.

class StringDataStore
{
    private string[] strArr = new string[10; // 内部数据存储
    public string this[int index]
    {
        get => strArr[index];
        set => strArr[index] = value;
    }
}

Indexador genérico

Os indexadores também podem ser genéricos. A seguir, uma classe genérica que inclui um indexador genérico.

class DataStore<T>
{
    private T[] store; 
    public DataStore()
    {
        store = new T[10;
    }
    public DataStore(int length)
    {
        store = new T[length];
    }
    public T this[int index]
    {
        get
        {
            if (index < 0 && index >= store.Length)
                throw new IndexOutOfRangeException("Index out of range");
                return store[index];
        }
        set
        {
            if (index < 0 || index >= store.Length)
                throw new IndexOutOfRangeException("Index out of range");
            store[index] = value;
        }
    }
    public int Length
    {
        get
        {
            return store.Length;
        }
    }
}

上面的泛型索引器可以与任何数据类型一起使用。以下示例演示了泛型索引器的用法。

DataStore<int> grades = new DataStore<int>();
grades[0] = 100;
grades[1] = 25;
grades[2] = 34;
grades[3] = 42;
grades[4] = 12;
grades[5] = 18;
grades[6] = 2;
grades[7] = 95;
grades[8] = 75;
grades[9] = 53;
for(int i = 0; i < grades.Length;i++)
    Console.WriteLine(grades[i]);
DataStore<string> names = new DataStore<string>(5);
names[0] = "Steve";
names[1] = "Bill";
names[2] = "James";
names[3] = "Ram";
names[4] = "Andy";
for(int i = 0; i < names.Length;i++)
    Console.WriteLine(names[i]);

重载索引器

可以用不同的数据类型重载索引。下面的示例使用int类型索引和string类型索引重载索引器。

class StringDataStore
{
    private string[] strArr = new string[10; // 内部数据存储
    // 整型索引器
    public string this[int index]
    {
        get
        {
            if(index < 0 || index >= strArr.Length)
                throw new IndexOutOfRangeException("Index out of range");
            return strArr[index];
        }
        set
        {
            if(index < 0 || index >= strArr.Length)
                throw new IndexOutOfRangeException("Index out of range");
            strArr[index] = value;
        }
    }
    // 字符串类型索引器
    public string this[string name]
    {
        get
        {
            foreach(string str in strArr){
                if(str.ToLower() == name.ToLower())        
                    return str;
                }
                    
            return null;
        }
    }
}
class Program
{
    static void Main(string[] args)
    {
        StringDataStore strStore = new StringDataStore();
        strStore[0] = "One";
        strStore[1] = "Two";
        strStore[2] = "Three";
        strStore[3] = "Four";
        
        Console.WriteLine(strStore["one"]);
        Console.WriteLine(strStore["two"]);
        Console.WriteLine(strStore["Three"]);
        Console.WriteLine(strStore["Four"]);
    }
}
Atenção: O indexador não permite parâmetros ref e out.