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

Indice de C# (Indexer)

Un indexador es una propiedad especial que permite acceder a una clase o estructura como si se accediera a un array interno. C# nos permite definir indexadores personalizados, indexadores genéricos y indexadores sobrecargados.

Se puede definir un indexador utilizando una propiedad con this y corchetes [].

Sintaxis

<return type> this[<parameter type> index]
{ 
   get{
        // Devolver valor desde la posición específica de la colección interna
    }
   set{ 
       // Establecer valor en la posición específica de la colección interna
    }
}

Definir indexador

A continuación, se muestra un ejemplo de cómo definir un indexador en una clase.

class StringDataStore
{
    private string[] strArr = new string[10; // Almacenamiento de datos interno
    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;
        }
    }
}

La clase StringDataStore define un indexador para el array privado strArr. Ahora, puede usar StringDataStore para agregar y recuperar valores de cadenas de manera similar a un array, como se muestra a continuación.

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]);
Salida:
Uno
Dos
Tres
Cuatro

Desde C# 7Inicialmente, se puede usar la sintaxis de expresión corporal para get y set.

class StringDataStore
{
    private string[] strArr = new string[10; // Almacenamiento de datos interno
    public string this[int index]
    {
        get => strArr[index];
        set => strArr[index] = value;
    }
}

Indexador genérico

Los indexadores también pueden ser genéricos. A continuación, se muestra una clase genérica que incluye un 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;
        }
    }
}

Los índices genéricos pueden utilizarse con cualquier tipo de datos. A continuación se muestra un ejemplo de uso del índice genérico.

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

Sobrecarga de índices

Se puede sobrecargar índices con diferentes tipos de datos. A continuación se muestra un ejemplo de sobrecarga de índices utilizando tipos de datos int y string.

class StringDataStore
{
    private string[] strArr = new string[10; // Almacenamiento de datos interno
    // Índice entero
    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;
        }
    }
    // Cajero de tipo de cadena
    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"]);
    }
}
Nota: Los indexadores no permiten parámetros ref y out.