Перегрузка операторов


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


Example

using System; // Define an DayOfWeek data type enum DayOfWeek { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday }; // Define a struct to store the methods and operators struct Day { private DayOfWeek day; // The constructor for the struct public Day(DayOfWeek initialDay) { day = initialDay; } // The overloaded + operator public static Day operator +(Day lhs, int rhs) { int intDay = (int)lhs.day; return new Day((DayOfWeek)((intDay + rhs) % 7)); } // An overloaded ToString method public override string ToString() { return day.ToString(); } } public class Program { static void Main() { // Create a new Days object called "today" Day today = new Day(DayOfWeek.Sunday); Console.WriteLine(today.ToString());   today = today + 1; Console.WriteLine(today.ToString());   today = today + 14; Console.WriteLine(today.ToString()); } }

Пример

using System;

// Define an DayOfWeek data type

enum DayOfWeek { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };

// Define a struct to store the methods and operators

struct Day

{

private DayOfWeek day;

// The constructor for the struct

public Day(DayOfWeek initialDay)

{

day = initialDay;

}

// The overloaded + operator

public static Day operator +(Day lhs, int rhs)

{

int intDay = (int)lhs.day;

return new Day((DayOfWeek)((intDay + rhs) % 7));

}

// An overloaded ToString method

public override string ToString()

{

return day.ToString();

}

}

public class Program

{

static void Main()

{

// Create a new Days object called "today"

Day today = new Day(DayOfWeek.Sunday);

Console.WriteLine(today.ToString());

today = today + 1;

Console.WriteLine(today.ToString());

today = today + 14;

Console.WriteLine(today.ToString());

}

}


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, используйте ключевое слово goto[43].

ß-----

 

 

Выражение, применяемое оператором 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.

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 выполняет более тяжелую работу[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);


Дата добавления: 2022-05-27; просмотров: 134;


Поиск по сайту:

Воспользовавшись поиском можно найти нужную информацию на сайте.

Поделитесь с друзьями:

Считаете данную информацию полезной, тогда расскажите друзьям в соц. сетях.
Poznayka.org - Познайка.Орг - 2016-2024 год. Материал предоставляется для ознакомительных и учебных целей.
Генерация страницы за: 0.017 сек.