Compartir a través de


Genéricos y matrices (Guía de programación de C#)

Las matrices unidimensionales que tienen un límite inferior de cero implementan IList<T>automáticamente . Esto le permite crear métodos genéricos que pueden usar el mismo código para recorrer en iteración matrices y otros tipos de colección. Esta técnica es principalmente útil para leer datos en colecciones. No se puede usar la IList<T> interfaz para agregar o quitar elementos de una matriz. Se producirá una excepción si intenta llamar a un IList<T> método como RemoveAt en una matriz en este contexto.

En el ejemplo de código siguiente se muestra cómo un único método genérico que toma un IList<T> parámetro de entrada puede recorrer en iteración una lista y una matriz, en este caso una matriz de enteros.

class Program
{
    static void Main()
    {
        int[] arr = [0, 1, 2, 3, 4];
        List<int> list = new List<int>();

        for (int x = 5; x < 10; x++)
        {
            list.Add(x);
        }

        ProcessItems<int>(arr);
        ProcessItems<int>(list);
    }

    static void ProcessItems<T>(IList<T> coll)
    {
        // IsReadOnly returns True for the array and False for the List.
        System.Console.WriteLine
            ("IsReadOnly returns {0} for this collection.",
            coll.IsReadOnly);

        // The following statement causes a run-time exception for the
        // array, but not for the List.
        //coll.RemoveAt(4);

        foreach (T item in coll)
        {
            System.Console.Write(item?.ToString() + " ");
        }
        System.Console.WriteLine();
    }
}

Consulte también