Value Type and Reference Type Arrays
Consider the following array declaration:
SomeType[] array4 = new SomeType[10]; |
The result of this statement depends on whether SomeType is a value type or a reference type. If it is a value type, the statement creates an array of 10 instances of the type SomeType. If SomeType is a reference type, the statement creates an array of 10 elements, each of which is initialized to a null reference.
Одномерные массив
Можно объявить массив из пяти целых чисел, как показано в следующем примере:
ß--
Массив содержит элементы с array[0] по array[4]. Оператор new служит для создания массива и инициализации элементов массива со значениями по умолчанию. В данном примере элементы массива инициализируются значением 0.
Массив, в котором хранятся строковые элементы, можно объявить таким же образом. Пример.
ß--
Инициализация массива
Массив можно инициализировать при объявлении. В этом случае спецификация ранга не нужна, поскольку она уже предоставлена по числу элементов в списке инициализации. Пример.
int[] array1 = new int[] { 1, 3, 5, 7, 9 }; |
Строковый массив можно инициализировать таким же образом. Ниже приведено объявление строкового массива, в котором каждый элемент инициализируется названием дня:
string[] weekDays = new string[] { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; |
При инициализации массива при объявлении можно использовать следующие сочетания клавиш:
int[] array2 = { 1, 3, 5, 7, 9 }; string[] weekDays2 = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; |
Можно объявить переменную массива без инициализации, но при присвоении массива этой переменной нужно использовать оператор new. Пример.
|
|
int[] array3; array3 = new int[] { 1, 3, 5, 7, 9 }; // OK //array3 = {1, 3, 5, 7, 9}; // Error |
В C# 3.0 поддерживаются неявно типизированные массивы.
Массивы типов значений и ссылочных типов.
Рассмотрим следующие объявления массива:
SomeType[] array4 = new SomeType[10]; |
Результат этого оператора зависит от того, является ли SomeType типом значения или ссылочным типом. Если это тип значения, оператор создает массив из 10 экземпляров типа SomeType. Если SomeType — ссылочный тип, оператор создает массив из 10 элементов, каждый из которых инициализируется нулевой ссылкой null.
Multidimensional Arrays
Arrays can have more than one dimension. For example, the following declaration creates a two-dimensional array of four rows and two columns:
int[,] array = new int[4, 2]; |
Also, the following declaration creates an array of three dimensions, 4, 2, and 3:
int[, ,] array1 = new int[4, 2, 3]; |
Array Initialization
You can initialize the array upon declaration as shown in the following example:
int[,] array2D = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } }; int[, ,] array3D = new int[,,] { { { 1, 2, 3 } }, { { 4, 5, 6 } } }; |
You can also initialize the array without specifying the rank:
int[,] array4 = { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } }; |
If you choose to declare an array variable without initialization, you must use the new operator to assign an array to the variable. For example:
int[,] array5; array5 = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } }; // OK //array5 = {{1,2}, {3,4}, {5,6}, {7,8}}; // Error |
You can also assign a value to an array element, for example:
|
|
array5[2, 1] = 25; |
The following code example initializes the array variables to default (except for jagged arrays):
int[,] array6 = new int[10, 10]; |
Многомерные массивы
Массивы могут иметь несколько измерений. Например, следующее объявление создает двумерный массив из четырех строк и двух столбцов.
int[,] array = new int[4, 2]; |
А следующее объявление создает трехмерный массив с количеством элементов 4, 2 и 3:
int[, ,] array1 = new int[4, 2, 3]; |
Инициализация массива
Массив можно инициализировать при объявлении, как показано в следующем примере:
int[,] array2D = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } }; int[, ,] array3D = new int[,,] { { { 1, 2, 3 } }, { { 4, 5, 6 } } }; |
Можно также инициализировать массив, не указывая его размерность:
int[,] array4 = { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } }; |
Если нужно создать переменную массива без инициализации, то необходимо использовать оператор 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 |
Можно также присвоить значение элементу массива, например:
array5[2, 1] = 25; |
В следующем примере кода элементы массива инициализируются значениями по умолчанию
int[,] array6 = new int[10, 10]; |
Jagged Arrays
A jagged array is an array whose elements are arrays. The elements of a jagged array can be of different dimensions and sizes. A jagged array is sometimes called an "array of arrays." The following examples show how to declare, initialize, and access jagged arrays.
|
|
The following is a declaration of a single-dimensional array that has three elements, each of which is a single-dimensional array of integers:
int[][] jaggedArray = new int[3][]; |
Before you can use jaggedArray, its elements must be initialized. You can initialize the elements like this:
jaggedArray[0] = new int[5]; jaggedArray[1] = new int[4]; jaggedArray[2] = new int[2]; |
Each of the elements is a single-dimensional array of integers. The first element is an array of 5 integers, the second is an array of 4 integers, and the third is an array of 2 integers.
It is also possible to use initializers to fill the array elements with values, in which case you do not need the array size. For example:
jaggedArray[0] = new int[] { 1, 3, 5, 7, 9 }; jaggedArray[1] = new int[] { 0, 2, 4, 6 }; jaggedArray[2] = new int[] { 11, 22 }; |
You can also initialize the array upon declaration like this:
int[][] jaggedArray2 = new int[][] { new int[] {1,3,5,7,9}, new int[] {0,2,4,6}, new int[] {11,22} }; |
You can use the following shorthand form. Notice that you cannot omit the new operator from the elements initialization because there is no default initialization for the elements:
int[][] jaggedArray3 = { new int[] {1,3,5,7,9}, new int[] {0,2,4,6}, new int[] {11,22} }; |
A jagged array is an array of arrays, and therefore its elements are reference types and are initialized to null.
Массивы массивов
Массив массивов — это массив, элементы которого сами являются массивами. Элементы массива массивов могут иметь различные размеры и измерения. Массивы массивов иногда также называются "невыровненными массивами". В следующих примерах показано, как выполняется объявление, инициализация и доступ к массивам массивов.
|
|
Ниже показано объявление одномерного массива, включающего три элемента, каждый из которых является одномерным массивом целых чисел.
int[][] jaggedArray = new int[3][]; |
Перед использованием jaggedArray его элементы нужно инициализировать. Сделать это можно следующим образом.
jaggedArray[0] = new int[5]; jaggedArray[1] = new int[4]; jaggedArray[2] = new int[2]; |
Каждый элемент представляет собой одномерный массив целых чисел. Первый элемент массива состоит из пяти целых чисел, второй — из четырех и третий — из двух.
Для заполнения элементов массива значениями можно также использовать инициализаторы, при этом размер массива знать не требуется. Пример.
jaggedArray[0] = new int[] { 1, 3, 5, 7, 9 }; jaggedArray[1] = new int[] { 0, 2, 4, 6 }; jaggedArray[2] = new int[] { 11, 22 }; |
Также массив можно инициализировать путем объявления.
int[][] jaggedArray2 = new int[][] { new int[] {1,3,5,7,9}, new int[] {0,2,4,6}, new int[] {11,22} }; |
Также можно использовать сокращенную форму. Обратите внимание, что при инициализации элементов оператор new опускать нельзя, так как инициализации по умолчанию для этих элементов не существует.
ß--
Невыровненный массив является массивом массивов, и поэтому его элементы являются ссылочными типами и инициализируются значением null.
You can access individual array elements like these examples:
// 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; |
It is possible to mix jagged and multidimensional arrays. The following is a declaration and initialization of a single-dimensional jagged array that contains two-dimensional array elements of different sizes:
int[][,] jaggedArray4 = new int[3][,] { new int[,] { {1,3}, {5,7} }, new int[,] { {0,2}, {4,6}, {8,10} }, new int[,] { {11,22}, {99,88}, {0,9} } }; |
You can access individual elements as shown in this example, which displays the value of the element [1,0] of the first array (value 5):
System.Console.Write("{0}", jaggedArray4[0][1, 0]); |
The method Length returns the number of arrays contained in the jagged array. For example, assuming you have declared the previous array, this line:
System.Console.WriteLine(jaggedArray4.Length); |
will return a value of 3.
Доступ к отдельным элементам массива выполняется следующим образом.
// 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; |
Массивы массивов можно смешивать с многомерными массивами. Ниже показано объявление и инициализация одномерного массива массивов, состоящего из двумерных элементов различного размера.
int[][,] jaggedArray4 = new int[3][,] { new int[,] { {1,3}, {5,7} }, new int[,] { {0,2}, {4,6}, {8,10} }, new int[,] { {11,22}, {99,88}, {0,9} } }; |
Доступ к отдельным элементам выполняется так, как показано в примере ниже, где отображено значение элемента [1,0] первого массива (значение 5).
System.Console.Write("{0}", jaggedArray4[0][1, 0]); |
Метод Length возвращает число массивов, содержащихся в массиве массивов. Например, если объявить предыдущий массив, строка кода
System.Console.WriteLine(jaggedArray4.Length); |
распечатает значение 3.
Example
This example builds an array whose elements are themselves arrays. Each one of the array elements has a different size.
class ArrayTest { static void Main() { // Declare the array of two elements: int[][] arr = new int[2][]; // Initialize the elements: arr[0] = new int[5] { 1, 3, 5, 7, 9 }; arr[1] = new int[4] { 2, 4, 6, 8 }; // Display the array elements: for (int i = 0; i < arr.Length; i++) { System.Console.Write("Element({0}): ", i); for (int j = 0; j < arr[i].Length; j++) { System.Console.Write("{0}{1}", arr[i][j], j == (arr[i].Length - 1) ? "" : " "); } System.Console.WriteLine(); } } } |
Output
Element(0): 1 3 5 7 9
Element(1): 2 4 6 8
Пример
В этом примере выполняется создание массива, элементы которого сами являются массивами. Каждый элемент массива имеет собственный размер.
ß--
Результат
Element(0): 1 3 5 7 9
Element(1): 2 4 6 8
Using foreach with Arrays
C# also provides the foreach statement. This statement provides a simple, clean way to iterate through the elements of an array. For example, the following code creates an array called numbers and iterates through it with the foreach statement:
int[] numbers = { 4, 5, 6, 1, 2, 3, -2, -1, 0 }; foreach (int i in numbers) { System.Console.WriteLine(i); } |
With multidimensional arrays, you can use the same method to iterate through the elements, for example:
int[,] numbers2D = new int[3, 2] { { 9, 99 }, { 3, 33 }, { 5, 55 } }; foreach (int i in numbers2D) { System.Console.Write("{0} ", i); } |
The output of this example is:
9 99 3 33 5 55
However, with multidimensional arrays, using a nested for loop gives you more control over the array elements.
Дата добавления: 2019-03-09; просмотров: 252; Мы поможем в написании вашей работы! |
Мы поможем в написании ваших работ!