logo search
CSharp_Prog_Guide

Передача многомерных массивов в качестве параметров

Инициализированный многомерный массив можно передать в метод. Например, если theArray является двумерным массивом:

PrintArray(theArray);

Метод, вызываемый в приведенной выше строке, может быть задан как:

void PrintArray(int[,] arr)

{

// method code

}

Новый массив можно инициализировать и передать за одно действие. Пример.

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

Example 2

Description

In this example, a two-dimensional array is initialized and passed to the PrintArray method, where its elements are displayed.

Code

class ArrayClass2D

{

static void PrintArray(int[,] arr)

{

// Display the array elements:

for (int i = 0; i < 4; i++)

{

for (int j = 0; j < 2; j++)

{

System.Console.WriteLine("Element({0},{1})={2}", i, j, arr[i, j]);

}

}

}

static void Main()

{

// Pass the array as a parameter:

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

}

}

Output 2

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