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

Foreach Loops

C# introduces a way of creating loops that may be new to C++ and C programmers: the foreach loop. Instead of creating a variable simply to index an array or other data structure such as a collection, the foreach loop does some of the hard work for you:

// An array of integers

int[] array1 = {0, 1, 2, 3, 4, 5};

foreach (int n in array1)

{

System.Console.WriteLine(n.ToString());

}

// An array of strings

string[] array2 = {"hello", "world"};

foreach (string s in array2)

{

System.Console.WriteLine(s);

}

Циклы

Циклом называется один или несколько операторов, повторяющихся заданное число раз или до тех пор, пока не будет выполнено определенное условие. Выбор типа цикла зависит от задачи программирования и личных предпочтений кодирования. Одним из основных отличий C# от других языков, таких как C++, является цикл foreach, разработанный для упрощения итерации по массиву или коллекции.

Циклы foreach

В C# представлен новый способ создания циклов, который может быть неизвестен программистам на C++ и C: цикл foreach. Вместо просто создания переменной для индексирования массива или другой структуры данных, такой как коллекция, цикл foreach выполняет более тяжелую работу41

// An array of integers

int[] array1 = {0, 1, 2, 3, 4, 5};

foreach (int n in array1)

{

System.Console.WriteLine(n.ToString());

}

// An array of strings

string[] array2 = {"hello", "world"};

foreach (string s in array2)

{

System.Console.WriteLine(s);

}

For Loops

Here is how the same loops would be created by using a for keyword:

// An array of integers

int[] array1 = {0, 1, 2, 3, 4, 5};

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

{

System.Console.WriteLine(array1[i].ToString());

}

// An array of strings

string[] array2 = {"hello", "world"};

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

{

System.Console.WriteLine(array2[i]);

}

while Loops

The while loop versions are in the following examples:

// An array of integers

int[] array1 = {0, 1, 2, 3, 4, 5};

int x = 0;

while (x < 6)

{

System.Console.WriteLine(array1[x].ToString());

x++;

}

// An array of strings

string[] array2 = {"hello", "world"};

int y = 0;

while (y < 2)

{

System.Console.WriteLine(array2[y]);

y++;

}

Циклыfor

Далее показано создание нескольких циклов с использованием ключевого слова for.

// An array of integers

int[] array1 = {0, 1, 2, 3, 4, 5};

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

{

System.Console.WriteLine(array1[i].ToString());

}

// An array of strings

string[] array2 = {"hello", "world"};

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

{

System.Console.WriteLine(array2[i]);

}

Циклы while

В следующих примерах показаны варианты цикла while.

----

do-while Loops

The do-while loop versions are in the following examples:

// An array of integers

int[] array1 = {0, 1, 2, 3, 4, 5};

int x = 0;

do

{

System.Console.WriteLine(array1[x].ToString());

x++;

} while(x < 6);

// An array of strings

string[] array2 = {"hello", "world"};

int y = 0;

do

{

System.Console.WriteLine(array2[y]);

y++;

} while(y < 2);

How to: Break Out of an Iterative Statement

This example uses the break statement to break out of a for loop when an integer counter reaches 10.

Example

for (int counter = 1; counter <= 1000; counter++)

{

if (counter == 10)

break;

System.Console.WriteLine(counter);

}

Compiling the Code

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

Циклыdo-while

В следующих примерах показаны варианты цикла do-while.

// An array of integers

int[] array1 = {0, 1, 2, 3, 4, 5};

int x = 0;

do

{

System.Console.WriteLine(array1[x].ToString());

x++;

} while(x < 6);

// An array of strings

string[] array2 = {"hello", "world"};

int y = 0;

do

{

System.Console.WriteLine(array2[y]);

y++;

} while(y < 2);

Разрыв итерационного оператора

В этом примере для разрыва цикла for по достижении счетчиком целых чисел значения "10" используется оператор break.

Пример

for (int counter = 1; counter <= 1000; counter++)

{

if (counter == 10)

break;

System.Console.WriteLine(counter);

}

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

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

Strings

A C# string is a group of one or more characters declared using the string keyword, which is a C# language shortcut for the System..::.String class. Strings in C# are much easier to use, and much less prone to programming errors, than character arrays in C or C++.

A string literal is declared using quotation marks, as shown in the following example:

string greeting = "Hello, World!";

You can extract substrings, and concatenate strings, like this:

string s1 = "orange";

string s2 = "red";

s1 += s2;

System.Console.WriteLine(s1); // outputs "orangered"

s1 = s1.Substring(2, 5);

System.Console.WriteLine(s1); // outputs "anger"

String objects are immutable in that they cannot be changed once created. Methods that act on strings actually return new string objects. Therefore, for performance reasons, large amounts of concatenation or other involved string manipulation should be performed with the StringBuilder class, as demonstrated in the code examples below.

Строки

Строка C# представляет собой группу одного или нескольких знаков, объявленных с помощью ключевого слова string, которое является ускоренным методом42 языка C# для класса System..::.String. В отличие от массивов знаков в C или C++, строки в C# гораздо проще в использовании и менее подвержены ошибкам программирования.

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

string greeting = "Hello, World!";

Можно извлекать подстроки и объединять строки, как показано в следующем примере.

string s1 = "orange";

string s2 = "red";

s1 += s2;

System.Console.WriteLine(s1); // outputs "orangered"

s1 = s1.Substring(2, 5);

System.Console.WriteLine(s1); // outputs "anger"

Строковые объекты являются неизменяемыми: после создания их нельзя изменить. Методы, работающие со строками, возвращают новые строковые объекты. Поэтому в целях повышения производительности большие объемы работы по объединению строк или другие операции следует выполнять в классе StringBuilder, как показано далее в примерах кода.

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