Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
CSharp_for_Beginners.doc
Скачиваний:
28
Добавлен:
23.11.2019
Размер:
2.4 Mб
Скачать

Массивы массивов

Одним из вариантов многомерного массива является массив массивов. Массив массивов представляет собой одномерный массив, в котором каждый элемент является массивом. Элементы массива не обязаны иметь одинаковый размер.

Объявить массив массивов можно следующим образом

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

Создание массива трех массивов. Эти массивы можно инициализировать следующим образом

jaggedArray[0] = new int[5];

jaggedArray[1] = new int[4];

jaggedArray[2] = new int[2];

Using the foreach Statement

The foreach statement is often used to access each element stored in an array:

int[] numbers = { 4, 5, 6, 1, 2, 3, -2, -1, 0 };

foreach (int i in numbers)

{

System.Console.WriteLine(i);

}

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

Оператор 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

Arrays of Objects

Creating an array of objects, rather than an array of simple data types such as integers, is a two-part process. First you declare the array, and then you must create the objects that are stored in the array. This example creates a class that defines an audio CD. It then creates an array that stores 20 audio CDs.

namespace CDCollection

{

// Define a CD type.

class CD

{

private string album;

private string artist;

private int rating;

public string Album

{

get {return album;}

set {album = value;}

}

public string Artist

{

get {return artist;}

set {artist = value;}

}

public int Rating

{

get {return rating;}

set {rating = value;}

}

}

class Program

{

static void Main(string[] args)

{

// Create the array to store the CDs.

CD[] cdLibrary = new CD[20];

// Populate the CD library with CD objects.

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

{

cdLibrary[i] = new CD();

}

// Assign details to the first album.

cdLibrary[0].Album = "See";

cdLibrary[0].Artist = "The Sharp Band";

cdLibrary[0].Rating = 10;

}

}}

Массивы объектов

Создание массива объектов в отличие от создания массива простых типов данных, например целочисленных, происходит в два этапа. Сначала необходимо объявить массив, а затем создать объекты для хранения в нем. В этом примере создается класс, определяющий аудио компакт-диск. Затем создается массив для хранения 20 аудио компакт-дисков.

namespace CDCollection

{

// Define a CD type.

class CD

{

private string album;

private string artist;

private int rating;

public string Album

{

get {return album;}

set {album = value;}

}

public string Artist

{

get {return artist;}

set {artist = value;}

}

public int Rating

{

get {return rating;}

set {rating = value;}

}

}

class Program

{

static void Main(string[] args)

{

// Create the array to store the CDs.

CD[] cdLibrary = new CD[20];

// Populate the CD library with CD objects.

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

{

cdLibrary[i] = new CD();

}

// Assign details to the first album.

cdLibrary[0].Album = "See";

cdLibrary[0].Artist = "The Sharp Band";

cdLibrary[0].Rating = 10;

}

}}

How to: Declare an Array

This example shows three different ways to declare different kinds of arrays: single-dimensional, multidimensional, and jagged.

Example

// Single-dimensional arrays.

int[] myArray1 = new int [5];

string[] myArray2 = new string[6];

// Multidimensional arrays.

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

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

// Jagged array (array of arrays)

int[][] myArray5 = new int[3][];

Compiling the Code

Copy the code and paste it into the Main method of a console application.

Robust Programming

Make sure you initialize the elements of the jagged array before using it, as follows:

myArray5[0] = new int[7];

myArray5[1] = new int[5];

myArray5[2] = new int[2];

Объявление массива

В этом примере показано три различных способа объявления нескольких видов массивов: одномерного, многомерного и массива массивов.

Пример

// Single-dimensional arrays.

int[] myArray1 = new int [5];

string[] myArray2 = new string[6];

// Multidimensional arrays.

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

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

// Jagged array (array of arrays)

int[][] myArray5 = new int[3][];

Компиляция кода

Скопируйте код и вставьте его в метод Main консольного приложения.

Надежное программирование

Убедитесь, что перед использованием массива массивов выполнена инициализация его элементов, как показано далее.

myArray5[0] = new int[7];

myArray5[1] = new int[5];

myArray5[2] = new int[2];

How to: Initialize an Array

This example shows three different ways to initialize different kinds of arrays: single-dimensional, multidimensional, and jagged.

Example

// Single-dimensional array (numbers).

int[] n1 = new int[4] {2, 4, 6, 8};

int[] n2 = new int[] {2, 4, 6, 8};

int[] n3 = {2, 4, 6, 8};

// Single-dimensional array (strings).

string[] s1 = new string[3] {"John", "Paul", "Mary"};

string[] s2 = new string[] {"John", "Paul", "Mary"};

string[] s3 = {"John", "Paul", "Mary"};

// Multidimensional array.

int[,] n4 = new int[3, 2] { {1, 2}, {3, 4}, {5, 6} };

int[,] n5 = new int[,] { {1, 2}, {3, 4}, {5, 6} };

int[,] n6 = { {1, 2}, {3, 4}, {5, 6} };

// Jagged array.

int[][] n7 = new int[2][] { new int[] {2,4,6}, new int[] {1,3,5,7,9} };

int[][] n8 = new int[][] { new int[] {2,4,6}, new int[] {1,3,5,7,9} };

int[][] n9 = { new int[] {2,4,6}, new int[] {1,3,5,7,9} };

Compiling the Code

Copy the code and paste it into the Main method of a console application.

Robust Programming

Array members are automatically initialized to the default initial value for the array type if the array is not initialized at the time it is declared. If the array declaration is a field of a type, then when the type is instantiated, the array will be set to its default value of null.

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]