Использование оператора foreach с массивами 


Мы поможем в написании ваших работ!



ЗНАЕТЕ ЛИ ВЫ?

Использование оператора foreach с массивами



В C# также предусмотрен оператор foreach. Этот оператор обеспечивает простой и понятный способ выполнения итерации элементов в массиве. Например, следующий код создает массив numbers и осуществляет его итерацию с помощью оператора foreach.

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

Этот же метод можно использовать для итерации элементов в многомерных массивах, например:

int[,] numbers2D = new int[3, 2] { { 9, 99 }, { 3, 33 }, { 5, 55 } }; foreach (int i in numbers2D) { System.Console.Write("{0} ", i); }

В результате выполнения примера получается следующий результат:

9 99 3 33 5 55

Однако для лучшего контроля элементов в многомерных массивах можно использовать вложенный цикл for.

 


Passing Arrays as Parameters

Arrays may be passed to methods as parameters. As arrays are reference types, the method can change the value of the elements.

Passing single-dimensional arrays as parameters

You can pass an initialized single-dimensional array to a method. For example:

PrintArray(theArray);

The method called in the line above could be defined as:

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

You can also initialize and pass a new array in one step. For example:

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

 


Передача массивов в качестве параметров

Массивы можно передавать в методы в качестве параметров. Поскольку массивы являются ссылочными типами, метод может изменять значение элементов.

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

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

PrintArray(theArray);

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

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

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

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

 


Example 1

Description

In the following example, a string array is initialized and passed as a parameter to the PrintArray method, where its elements are displayed:

Code

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 Main() { // Declare and initialize an array: string[] weekDays = new string[] { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };   // Pass the array as a parameter: PrintArray(weekDays); } }

Output 1

Sun Mon Tue Wed Thu Fri Sat

 


Пример 1

Описание

В следующем примере массив строк инициализируется и передается в качестве параметра в метод PrintArray, где отображаются его элементы:

Код

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 Main() { // Declare and initialize an array: string[] weekDays = new string[] { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };   // Pass the array as a parameter: PrintArray(weekDays); } }

Результат 1

Sun Mon Tue Wed Thu Fri Sat


Passing multidimensional arrays as parameters

You can pass an initialized multidimensional array to a method. For example, if theArray is a two dimensional array:

PrintArray(theArray);

The method called in the line above could be defined as:

void PrintArray(int[,] arr) { // method code }

You can also initialize and pass a new array in one step. For example:

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

 


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

Инициализированный многомерный массив можно передать в метод. Например, если 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


Пример 2

Описание

В данном примере двумерный массив строк инициализируется и передается в метод PrintArray, где отображаются его элементы.

Код

ß--



Поделиться:


Последнее изменение этой страницы: 2017-01-19; просмотров: 197; Нарушение авторского права страницы; Мы поможем в написании вашей работы!

infopedia.su Все материалы представленные на сайте исключительно с целью ознакомления читателями и не преследуют коммерческих целей или нарушение авторских прав. Обратная связь - 3.144.77.71 (0.006 с.)