Compartilhar via


Passando matrizes como argumentos (Guia de Programação em C#)

Arrays podem ser passados como argumentos para os parâmetros do método. Como os arrays são tipos de referência, o método pode alterar o valor dos elementos.

Matrizes unidimensionais de passagem como argumentos

Você pode passar uma matriz unidimensional inicializada para um método. Por exemplo, a instrução a seguir envia uma matriz para um método de impressão.

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

O código a seguir mostra uma implementação parcial do método de impressão.

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

Você pode inicializar e passar uma nova matriz em uma única etapa, conforme é mostrado no exemplo a seguir.

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

Exemplo

Descrição

No exemplo a seguir, uma matriz de seqüências é inicializada e passada como um argumento para um PrintArray método para seqüências de caracteres. O método exibe os elementos da matriz. Métodos de Avançar, ChangeArray e ChangeArrayElement são chamados para demonstrar que o envio de um argumento de matriz por valor não impede que as alterações para os elementos da matriz.

Código

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

Passando a matrizes multidimensionais como argumentos

Você passa uma matriz multidimensional inicializada para um método da mesma forma que você passar uma matriz unidimensional.

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

O código a seguir mostra uma declaração parcial de um método de impressão que aceita uma matriz bidimensional, como seu argumento.

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

Você pode inicializar e passar uma nova matriz em uma única etapa, conforme é mostrado no exemplo a seguir.

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

Exemplo

Descrição

No exemplo a seguir, uma matriz bidimensional de números inteiros é inicializada e passada para o Print2DArray método. O método exibe os elementos da matriz.

Código

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
    */

Consulte também

Referência

Matrizes (Guia de Programação em C#)

Matrizes unidimensionais (Guia de Programação em C#)

Matrizes multidimensionais (Guia de Programação em C#)

Matrizes denteadas (Guia de Programação em C#)

Conceitos

Guia de Programação em C#