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

Реляционные операторы

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

Оператор

Назначение

==

Проверка на равенство.

!=

Проверка на неравенство.

>

Больше.

<

Меньше.

>=

Больше или равно.

<=

Меньше или равно.

Пример

int x = int.Parse(System.Console.ReadLine());

if (x > 100)

{

System.Console.WriteLine("X is greater than 100");

}

Logical Condition Operators

The logical operators are used to create more flexible condition statements by combining multiple clauses:

Operator

Purpose

&&

Conditional AND.

||

Conditional OR.

!

Conditional NOT.

Example

int x = int.Parse(System.Console.ReadLine());

if ((x >= 100) && (x <= 200))

{

System.Console.WriteLine("X is between 100 and 200");

}

More Advanced Math Operators

To perform more advanced mathematical operations, for example, trigonometry, use the Math Frameworks class. In this example, the Sin (sine) and Sqrt (square root) methods, and PI constant are being used:

Example

double d = System.Math.Sin(System.Math.PI/2);

double e = System.Math.Sqrt(144);

Логические условные операторы

Логические операторы используются для создания более гибких условных инструкций путем объединения нескольких предложений.

Оператор

Назначение

&&

Условное И.

||

Условное ИЛИ.

!

Условное НЕТ.

Пример

int x = int.Parse(System.Console.ReadLine());

if ((x >= 100) && (x <= 200))

{

System.Console.WriteLine("X is between 100 and 200");

}

Несколько дополнительных математических операторов

Для выполнения более сложных математических операций, например в тригонометрии, используется класс Math. В этом примере используются методы Sin (вычисление синуса) и Sqrt (вычисление квадратного корня) и константа PI.

Пример

double d = System.Math.Sin(System.Math.PI/2);

double e = System.Math.Sqrt(144);

Operator Overloading

C# supports operator overloading; this allows you to redefine operators to be more meaningful when used with your own data types. In the following example, a struct is created, and it stores a single day of the week in a variable type defined by an enumeration. The addition operator is overloaded to make it possible to add an integer number of days to the current day, and return a new day of the week. So, Sunday with one day added to it returns Monday.

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

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.

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