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

Decisions and Branching

Changing the flow of control in a program in response to some kind of input or calculated value is an essential part of a programming language. C# provides the ability to change the flow of control, either unconditionally, by jumping to a new location in the code, or conditionally, by performing a test.

Remarks

The simplest form of conditional branching uses the if construct. You can use an else clause with the if construct, and if constructs can be nested.

using System;

class Program

{

static void Main()

{

int x = 1;

int y = 1;

if (x == 1)

Console.WriteLine("x == 1");

else

Console.WriteLine("x != 1");

if (x == 1)

{

if (y == 2)

{

Console.WriteLine("x == 1 and y == 2");

}

else

{

Console.WriteLine("x == 1 and y != 2");

}

}

}

}

Note:

Unlike C and C++, if statements require Boolean values. For example, it is not permissible to have a statement that doesn't get evaluated to a simple True or False, such as (a=10). In C#, 0 cannot be substituted for False and 1, or any other value, for True.

Выбор и ветвление

Изменение потока управления в программе в ответ на какой либо ввод или вычисляемое значение является важной частью языка программирования. C# предоставляет возможность изменить поток управления либо безусловным способом — за счет перехода к новому расположению в коде, либо условным — за счет выполнения теста.

В самой простой форме условного ветвления используется конструкция if. Предложение else можно использовать с конструкцией if, а конструкции if могут быть вложенными.

------

Примечание.

В отличие от C и C++, операторы if требуют логических значений. Например, использование оператора, которому не задано простое значение True или False, например (a=10), не допускается. В C# ноль нельзя заменить на False, а 1 или другое значение на True.

The statements following the if and else keywords can be single lines of code as shown in the first if-else statement in the previous code example, or a block of statements contained in braces as shown in the second if-else statement. It is permissible to nest if-else statements, but it is usually considered better programming practice to use a switch statement instead.

A switch statement can perform multiple actions depending on the value of a given expression. The code between the case statement and the break keyword is executed if the condition is met. If you want the flow of control to continue to another case statement, use the goto keyword.

using System;

class Program

{

static void Main()

{

int x = 3;

switch (x)

{

case 1:

Console.WriteLine("x is equal to 1");

break;

case 2:

Console.WriteLine("x is equal to 2");

break;

case 3:

goto default;

default:

Console.WriteLine("x is equal to neither 1 nor 2");

break;

}

}

}

The expression that the switch statement uses to determine the case to execute must use the Built-in Data Types, such as int or string; you cannot use more complex user-defined types.

Unlike Visual Basic, in C# the condition must be a constant value. For example, it is not permissible to compare the expression to a range of values.

Операторы, следующие за ключевыми словами if и else, могут представлять одну строку кода, как показано в первом операторе if-else в предыдущем примере кода, или блок операторов, заключенных в скобки, как показано во втором операторе if-else. Вложение операторов if-else является допустимым, однако в программировании лучшим способом считается использование оператора switch.

В зависимости от значения заданного выражения оператор switch может выполнять несколько действий. Код между оператором case и ключевым словом break выполняется при соблюдении данного условия. Если требуется, чтобы поток управления продолжался в другом операторе case, используйте ключевое слово goto40.

-----

Выражение, применяемое оператором switch для определения возможности выполнения, должно использовать Встроенные типы данных, такие как int или string; более сложные пользовательские типы использовать нельзя.

Loops

A loop is a statement, or set of statements, that are repeated for a specified number of times or until some condition is met. The type of loop you use depends on your programming task and your personal coding preference. One main difference between C# and other languages, such as C++, is the foreach loop, designed to simplify iterating through arrays or collections.

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