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

Циклы foreach

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

// 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, которое является ускоренным методом45 языка 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, как показано далее в примерах кода.

Working with Strings

Escape Characters

Escape characters such as "\n" (new line) and "\t" (tab) can be included in strings. The line:

string hello = "Hello\nWorld!";

is the same as:

Hello

World!

If you want to include a backward slash, it must be preceded with another backward slash. The following string:

string filePath = "\\\\My Documents\\";

is actually the same as:

\\My Documents\

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