c # tipo de matriz

Tipo de matriz

En C #, una matriz es en realidad un objeto, es una estructura de datos que contiene varias variables del mismo tipo.

Descripción general de la matriz

La matriz tiene las siguientes propiedades:

  • Las matrices pueden ser unidimensional , multi-dimensional o escalonados en.
  • El valor predeterminado de los elementos de la matriz numérica se establece en cero, y el valor predeterminado de los elementos de referencia se establece en nulo.
  • Una matriz escalonada es una matriz de matrices, por lo que sus elementos son tipos de referencia e inicializados como nulos.
  • El índice de la matriz comienza desde cero: el índice de la matriz con n elementos es de 0 a n-1.
  • Los elementos de matriz pueden ser de cualquier tipo, incluidos los tipos de matriz.
  • tipo de matriz desde el tipo de base abstracta matriz deriva tipo de referencia . Dado que este tipo implementa IEnumerable e IEnumerable <T> , puede usar la iteración foreach en todas las matrices en C # .

Matriz unidimensional

int[] array = new int[5];
string[] stringArray = new string[6];

Esta matriz contiene elementos desde la matriz [0] a la matriz [4]. El nuevo operador se utiliza para crear una matriz e inicializar los elementos de la matriz a sus valores predeterminados. En este ejemplo, todos los elementos de la matriz se inicializan a cero.

Inicialización de matriz

int[] array1 = new int[] { 1, 3, 5, 7, 9 };
string[] weekDays = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };

Matriz multidimensional

Las matrices pueden tener múltiples dimensiones. Por ejemplo, la siguiente declaración crea una matriz bidimensional con cuatro filas y dos columnas.

int[,] array = new int[4, 2];

Declare crear una matriz tridimensional (4, 2 y 3).

int[, ,] array1 = new int[4, 2, 3];

Inicialización de matriz

// Two-dimensional array.
int[,] array2D = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
// The same array with dimensions specified.
int[,] array2Da = new int[4, 2] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
// A similar array with string elements.
string[,] array2Db = new string[3, 2] { { "one", "two" }, { "three", "four" },
                                        { "five", "six" } };

// Three-dimensional array.
int[, ,] array3D = new int[,,] { { { 1, 2, 3 }, { 4, 5, 6 } }, 
                                 { { 7, 8, 9 }, { 10, 11, 12 } } };
// The same array with dimensions specified.
int[, ,] array3Da = new int[2, 2, 3] { { { 1, 2, 3 }, { 4, 5, 6 } }, 
                                       { { 7, 8, 9 }, { 10, 11, 12 } } };

// Accessing array elements.
System.Console.WriteLine(array2D[0, 0]);
System.Console.WriteLine(array2D[0, 1]);
System.Console.WriteLine(array2D[1, 0]);
System.Console.WriteLine(array2D[1, 1]);
System.Console.WriteLine(array2D[3, 0]);
System.Console.WriteLine(array2Db[1, 0]);
System.Console.WriteLine(array3Da[1, 0, 1]);
System.Console.WriteLine(array3D[1, 1, 2]);

// Output:
// 1
// 2
// 3
// 4
// 7
// three
// 8
// 12

También puede inicializar una matriz sin especificar un nivel.

int[,] array4 = { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };

Si elige declarar una variable de matriz pero no la inicializa, debe usar el nuevo operador para asignar una matriz a esta variable. El siguiente ejemplo muestra el uso de new.

int[,] array5;
array5 = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };   // OK
//array5 = {{1,2}, {3,4}, {5,6}, {7,8}};   // Error

Asignar valores a elementos de matriz específicos.

array5[2, 1] = 25;

Inicialice los elementos de la matriz a los valores predeterminados (excepto las matrices escalonadas):

int[,] array6 = new int[10, 10];

Matriz escalonada

Una matriz intercalada es una matriz cuyos elementos son matrices. Las dimensiones y tamaños de los elementos de la matriz intercalada pueden ser diferentes. Las matrices intercaladas a veces se denominan "matrices de matrices".

int[][] jaggedArray = new int[3][];

Debe inicializar los elementos de jaggedArray antes de poder usarlo.

jaggedArray[0] = new int[5];
jaggedArray[1] = new int[4];
jaggedArray[2] = new int[2];

Cada elemento es una matriz entera unidimensional. El primer elemento es una matriz de 5 enteros, el segundo es una matriz de 4 enteros y el tercero es una matriz de 2 enteros.

jaggedArray[0] = new int[] { 1, 3, 5, 7, 9 };
jaggedArray[1] = new int[] { 0, 2, 4, 6 };
jaggedArray[2] = new int[] { 11, 22 };

Inicialice la matriz al declararla

int[][] jaggedArray2 = new int[][] 
{
    new int[] {1,3,5,7,9},
    new int[] {0,2,4,6},
    new int[] {11,22}
};

Acceda a elementos de matriz individuales:

// Assign 77 to the second element ([1]) of the first array ([0]):
jaggedArray3[0][1] = 77;

// Assign 88 to the second element ([1]) of the third array ([2]):
jaggedArray3[2][1] = 88;

Matriz usando foreach

Cree una matriz llamada números e itere a través de la matriz con una instrucción foreach:

int[] numbers = { 4, 5, 6, 1, 2, 3, -2, -1, 0 };
foreach (int i in numbers)
{
    System.Console.Write("{0} ", i);
}
// Output: 4 5 6 1 2 3 -2 -1 0

Matriz multidimensional, puede usar el mismo método para recorrer los elementos

int[,] numbers2D = new int[3, 2] { { 9, 99 }, { 3, 33 }, { 5, 55 } };
// Or use the short form:
// int[,] numbers2D = { { 9, 99 }, { 3, 33 }, { 5, 55 } };

foreach (int i in numbers2D)
{
    System.Console.Write("{0} ", i);
}
// Output: 9 99 3 33 5 55

Matriz unidimensional pasada al método

int[] theArray = { 1, 3, 5, 7, 9 };
PrintArray(theArray);

Implementación parcial del método de impresión.

void PrintArray(int[] arr)
{
    // Method code.
}

Inicializar y pasar una nueva matriz

PrintArray(new int[] { 1, 3, 5, 7, 9 });

Ejemplo oficial

class ArrayClass
{
    static void PrintArray(string[] arr)
    {
        for (int i = 0; i < arr.Length; i++)
        {
            System.Console.Write(arr[i] + "{0}", i < arr.Length - 1 ? " " : "");
        }
        System.Console.WriteLine();
    }

    static void ChangeArray(string[] arr)
    {
        // The following attempt to reverse the array does not persist when
        // the method returns, because arr is a value parameter.
        arr = (arr.Reverse()).ToArray();
        // The following statement displays Sat as the first element in the array.
        System.Console.WriteLine("arr[0] is {0} in ChangeArray.", arr[0]);
    }

    static void ChangeArrayElements(string[] arr)
    {
        // The following assignments change the value of individual array 
        // elements. 
        arr[0] = "Sat";
        arr[1] = "Fri";
        arr[2] = "Thu";
        // The following statement again displays Sat as the first element
        // in the array arr, inside the called method.
        System.Console.WriteLine("arr[0] is {0} in ChangeArrayElements.", arr[0]);
    }

    static void Main()
    {
        // Declare and initialize an array.
        string[] weekDays = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };

        // Pass the array as an argument to PrintArray.
        PrintArray(weekDays);

        // ChangeArray tries to change the array by assigning something new
        // to the array in the method. 
        ChangeArray(weekDays);

        // Print the array again, to verify that it has not been changed.
        System.Console.WriteLine("Array weekDays after the call to ChangeArray:");
        PrintArray(weekDays);
        System.Console.WriteLine();

        // ChangeArrayElements assigns new values to individual array
        // elements.
        ChangeArrayElements(weekDays);

        // The changes to individual elements persist after the method returns.
        // Print the array, to verify that it has been changed.
        System.Console.WriteLine("Array weekDays after the call to ChangeArrayElements:");
        PrintArray(weekDays);
    }
}
// Output: 
// Sun Mon Tue Wed Thu Fri Sat
// arr[0] is Sat in ChangeArray.
// Array weekDays after the call to ChangeArray:
// Sun Mon Tue Wed Thu Fri Sat
// 
// arr[0] is Sat in ChangeArrayElements.
// Array weekDays after the call to ChangeArrayElements:
// Sat Fri Thu Wed Thu Fri Sat

Matriz multidimensional pasada al método

int[,] theArray = { { 1, 2 }, { 2, 3 }, { 3, 4 } };
Print2DArray(theArray);

Este método acepta una matriz bidimensional como su parámetro.

void Print2DArray(int[,] arr)
{
    // Method code.
}

Inicializar y pasar una nueva matriz

Print2DArray(new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } });

Ejemplo oficial

class ArrayClass2D
{
    static void Print2DArray(int[,] arr)
    {
        // Display the array elements.
        for (int i = 0; i < arr.GetLength(0); i++)
        {
            for (int j = 0; j < arr.GetLength(1); j++)
            {
                System.Console.WriteLine("Element({0},{1})={2}", i, j, arr[i, j]);
            }
        }
    }
    static void Main()
    {
        // Pass the array as an argument.
        Print2DArray(new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } });

        // Keep the console window open in debug mode.
        System.Console.WriteLine("Press any key to exit.");
        System.Console.ReadKey();
    }
}
    /* Output:
        Element(0,0)=1
        Element(0,1)=2
        Element(1,0)=3
        Element(1,1)=4
        Element(2,0)=5
        Element(2,1)=6
        Element(3,0)=7
        Element(3,1)=8
    */

Use ref y out para pasar una matriz

Antes de usar el parámetro de tipo de matriz, se le debe asignar un valor, es decir, el destinatario debe asignarle un valor.

static void TestMethod1(out int[] arr)
{
    arr = new int[10];   // definite assignment of arr
}

Como con todos los parámetros de referencia , la persona que llama debe asignar explícitamente los parámetros de referencia del tipo de matriz. Por lo tanto, no hay necesidad de asignación explícita por parte del destinatario. Puede cambiar el parámetro de referencia del tipo de matriz al resultado de la llamada.

static void TestMethod2(ref int[] arr)
{
    arr = new int[10];   // arr initialized to a different array
}

Ejemplos

Declare la matriz theArray en la persona que llama (método Main) e inicialice esta matriz en el método FillArray. Luego devuelva los elementos de la matriz a la persona que llama y la pantalla.

class TestOut
{
    static void FillArray(out int[] arr)
    {
        // Initialize the array:
        arr = new int[5] { 1, 2, 3, 4, 5 };
    }

    static void Main()
    {
        int[] theArray; // Initialization is not required

        // Pass the array to the callee using out:
        FillArray(out theArray);

        // Display the array elements:
        System.Console.WriteLine("Array elements are:");
        for (int i = 0; i < theArray.Length; i++)
        {
            System.Console.Write(theArray[i] + " ");
        }

        // Keep the console window open in debug mode.
        System.Console.WriteLine("Press any key to exit.");
        System.Console.ReadKey();
    }
}
    /* Output:
        Array elements are:
        1 2 3 4 5        
    */

Inicialice la matriz theArray en la persona que llama (método Main) y páselo al método FillArray utilizando el parámetro ref. Actualice algunos elementos de la matriz en el método FillArray. Luego devuelva los elementos de la matriz a la persona que llama y visualice

class TestRef
{
    static void FillArray(ref int[] arr)
    {
        // Create the array on demand:
        if (arr == null)
        {
            arr = new int[10];
        }
        // Fill the array:
        arr[0] = 1111;
        arr[4] = 5555;
    }

    static void Main()
    {
        // Initialize the array:
        int[] theArray = { 1, 2, 3, 4, 5 };

        // Pass the array using ref:
        FillArray(ref theArray);

        // Display the updated array:
        System.Console.WriteLine("Array elements are:");
        for (int i = 0; i < theArray.Length; i++)
        {
            System.Console.Write(theArray[i] + " ");
        }

        // Keep the console window open in debug mode.
        System.Console.WriteLine("Press any key to exit.");
        System.Console.ReadKey();
    }
}
    /* Output:
        Array elements are:
        1111 2 3 4 5555
    */

Matriz tipada implícitamente

Cómo crear una matriz tipada implícitamente:

class ImplicitlyTypedArraySample
{
    static void Main()
    {
        var a = new[] { 1, 10, 100, 1000 }; // int[]
        var b = new[] { "hello", null, "world" }; // string[]

        // single-dimension jagged array
        var c = new[]   
{  
    new[]{1,2,3,4},
    new[]{5,6,7,8}
};

        // jagged array of strings
        var d = new[]   
{
    new[]{"Luca", "Mads", "Luke", "Dinesh"},
    new[]{"Karen", "Suma", "Frances"}
};
    }
}

Al crear un tipo anónimo que contiene una matriz, la matriz debe escribirse implícitamente en el inicializador de objeto para ese tipo. En el siguiente ejemplo, contactos es una matriz de tipos anónimos tipada implícitamente, donde cada tipo anónimo contiene una matriz llamada PhoneNumbers. Tenga en cuenta que la palabra clave var no se usa internamente en el inicializador de objeto.

var contacts = new[] 
{
    new {
            Name = " Eugene Zabokritski",
            PhoneNumbers = new[] { "206-555-0108", "425-555-0001" }
        },
    new {
            Name = " Hanying Feng",
            PhoneNumbers = new[] { "650-555-0199" }
        }
};

Supongo que te gusta

Origin www.cnblogs.com/ouyangkai/p/12753831.html
Recomendado
Clasificación