Wei-Meng Lee - C# 2008 Programmer's Reference

Здесь есть возможность читать онлайн «Wei-Meng Lee - C# 2008 Programmer's Reference» весь текст электронной книги совершенно бесплатно (целиком полную версию без сокращений). В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Город: Indianapolis, Год выпуска: 2009, ISBN: 2009, Издательство: Wiley Publishing, Inc., Жанр: Программирование, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.

C# 2008 Programmer's Reference: краткое содержание, описание и аннотация

Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «C# 2008 Programmer's Reference»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.

C# 2008 Programmers Reference provides a concise and thorough reference on all aspects of the language. Each chapter contains detailed code samples that provide a quick and easy way to understand the key concepts covered.

C# 2008 Programmer's Reference — читать онлайн бесплатно полную книгу (весь текст) целиком

Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «C# 2008 Programmer's Reference», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать
Figure 131 That means you can use the Rankproperty to learn the dimension of - фото 186

Figure 13-1

That means you can use the Rankproperty to learn the dimension of an array. To find out how many elements are contained within an array, you can use the Lengthproperty. The following statements produce the output shown in Figure 13-2.

Console.WriteLine("Dimension of num is {0}", num.Rank);

Console.WriteLine("Number of elements in num is {0}", num.Length);

Figure 132 To sort an array you can use the static Sortmethod in the - фото 187

Figure 13-2

To sort an array, you can use the static Sort()method in the Arrayclass:

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

Array.Sort(num);

foreach (int i in num) Console.WriteLine(i);

These statements print out the array in sorted order:

1

2

3

4

5

Accessing Array Elements

To access an element in an array, you specify its index, as shown in the following statements:

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

Console.WriteLine(num[0]); //---1---

Console.WriteLine(num[1]); //---2---

Console.WriteLine(num[2]); //---3---

Console.WriteLine(num[3]); //---4---

Console.WriteLine(num[4]); //---5---

The index of an array starts from 0 to n-1 . For example, numhas size of 5 so the index runs from 0 to 4.

You usually use a loop construct to run through the elements in an array. For example, you can use the for statement to iterate through the elements of an array:

for (int i = 0; i < num.Length; i++)

Console.WriteLine(num[i]);

You can also use the foreachstatement, which is a clean way to iterate through the elements of an array quickly:

foreach (int n in num)

Console.WriteLine(n);

Multidimensional Arrays

So far the arrays you have seen are all one-dimensional ones. Arrays may also be multidimensional. To declare a multidimensional array, you can the comma ( ,) separator. The following declares xy to be a 2-dimensional array:

int[,] xy;

To initialize the two-dimensional array, you use the new keyword together with the size of the array:

xy = new int[3,2];

With this statement, xy can now contain six elements (three rows and two columns). To initialize xy with some values, you can use the following statement:

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

The following statement declares a three-dimensional array:

int[, ,] xyz;

To initialize it, you again use the new keyword together with the size of the array:

xyz = new int[2, 2, 2];

To initialize the array with some values, you can use the following:

int[, ,] xyz;

xyz = new int[,,] {

{ { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } }

};

To access all the elements in the three-dimensional array, you can use the following code snippet:

for (int x = xyz.GetLowerBound(0); x <= xyz.GetUpperBound(0); x++)

for (int y = xyz.GetLowerBound(1); y <= xyz.GetUpperBound(1); y++)

for (int z = xyz.GetLowerBound(2); z <= xyz.GetUpperBound(2); z++)

Console.WriteLine(xyz[x, y, z]);

The Arrayabstract base class contains the GetLowerBound()and GetUpperBound()methods to let you know the size of an array. Both methods take in a single parameter, which indicates the dimension of the array about which you are inquiring. For example, GetUpperBound(0)returns the size of the first dimension, GetUpperBound(1)returns the size of the second dimension, and so on.

You can also use the foreach statement to access all the elements in a multidimensional array:

foreach (int n in xyz)

Console.WriteLine(n);

These statements print out the following:

1

2

3

4

5

6

7

8

Arrays of Arrays: Jagged Arrays

An array's elements can also contain arrays. An array of arrays is known as a jagged array. Consider the following statements:

Point[][] lines = new Point[5][];

lines[0] = new Point[4];

lines[1] = new Point[15];

lines[2] = new Point[7];

lines[3] = ...

lines[4] = ...

Here, linesis a jagged array. It has five elements and each element is a Pointarray. The first element is an array containing four elements, the second contains 15 elements, and so on.

The Pointclass represents an ordered pair of integer x- and y-coordinates that defines a point in a two-dimensional plane.

You can use the array initializer to initialize the individual array within the lines array, like this:

Point[][] lines = new Point[3][];

lines[0] = new Point[] {

new Point(2, 3), new Point(4, 5)

}; //---2 points in lines[0]---

lines[1] = new Point[] {

new Point(2, 3), new Point(4, 5), new Point(6, 9)

}; //---3 points in lines[1]----

lines[2] = new Point[] {

new Point(2, 3)

}; //---1 point in lines[2]---

To access the individual Pointobjects in the lines array, you first specify which Pointarray you want to access, followed by the index for the elements in the Point array, like this:

//---get the first point in lines[0]---

Point ptA = lines[0][0]; //----(2,3)

//---get the third point in lines[1]---

Point ptB = lines[1][2]; //---(6,9)---

A jagged array can also contain multidimensional arrays. For example, the following declaration declares nums to be a jagged array with each element pointing to a two-dimensional array:

int[][,] nums = new int[][,] {

new int[,] {{ 1, 2 }, { 3, 4 }},

new int[,] {{ 5, 6 }, { 7, 8 }}

};

To access an individual element within the jagged array, you can use the following statements:

Console.WriteLine(nums[0][0, 0]); //---1---

Console.WriteLine(nums[0][0, 1]); //---2---

Console.WriteLine(nums[0][1, 0]); //---3---

Console.WriteLine(nums[0][1, 1]); //---4---

Console.WriteLine(nums[1][0, 0]); //---5---

Console.WriteLine(nums[1][0, 1]); //---6---

Console.WriteLine(nums[1][1, 0]); //---7---

Console.WriteLine(nums[1][1, 1]); //---8---

Used on a jagged array, the Lengthproperty of the Array abstract base class returns the number of arrays contained in the jagged array:

Console.WriteLine(nums.Length); //---2---

Parameter Arrays

In C#, you can pass variable numbers of parameters into a function/method using a feature known as parameter arrays. Consider the following statements:

Читать дальше
Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Похожие книги на «C# 2008 Programmer's Reference»

Представляем Вашему вниманию похожие книги на «C# 2008 Programmer's Reference» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.


Отзывы о книге «C# 2008 Programmer's Reference»

Обсуждение, отзывы о книге «C# 2008 Programmer's Reference» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.

x