Operators
In C#, operators have similar syntax to other C-style programming languages. Operators are used to do calculations, assign values to variables, test for equality or inequality, and perform other operations.
The following sections list some of the most commonly used operators in C#.
Assignment and Equality Operators
In C#, the equals sign (=) operator has the same functionality as in C and C++:
Operator | Purpose |
= | Assigns a value. |
== | Tests for equality. |
Example
int x = 100; if (x == 100) { System.Console.WriteLine("X is equal to 100"); } |
Операторы
Синтаксис операторов в C# сходен с синтаксисом других языков программирования в стиле языка C. Операторы используются для выполнения вычислений, назначения значений, проверки на равенство и неравенство и т. д.
В следующих разделах представлен список наиболее часто используемых операторов в C#.
Операторы равенства и назначения
В C# оператор знака равенства (=) имеет ту же функциональность, что и в C и C++.
Оператор | Назначение |
= | Присваивание значения. |
== | Проверка на равенство. |
Пример
int x = 100;
if (x == 100)
{
System.Console.WriteLine("X is equal to 100");
}
Mathematical and Logical Operators
The following is a list of the basic mathematical operators, listed in order of precedence. Use parentheses to force other ordering.
Operator | Purpose |
*, /, % | Multiplication, Division, Modulus |
+, - | Addition , Subtraction |
& | Logical AND |
^ | Logical XOR |
| | Logical OR |
Example
int x = 1; int y = x + 10 * 100; // multiplication first y = 1001 int z = (x + 10) * 100; // addition first z = 1100 |
Логические и математические операторы
Далее представлен список основных математических операторов, указанных в порядке приоритета. Для упорядочения по другим принципам используйте скобки.
Оператор | Назначение |
*, /, % | Умножение, деление, остаток от деления |
+, - | Сложение, вычитание |
& | Логическое И |
^ | Логическое исключающее ИЛИ |
| | Логическое ИЛИ |
Пример
int x = 1;
int y = x + 10 * 100; // multiplication first y = 1001
int z = (x + 10) * 100; // addition first z = 1100
Increment and Decrement operators
C/C++ style shortcuts are supported, including postfix and prefix operators, as shown in these examples:
Operator | Purpose |
v++ | Increment variable v by 1. |
v+=n | Increment variable v by n. |
v*=n | Multiply variable v by n. |
v-=n | Subtract n from variable v. |
Example
int x = 0;
int y = x++; // x is 1, y is 0
System.Console.WriteLine("{0} {1}", x, y);
int z = ++x; // x is 2, z is 2
System.Console.WriteLine("{0} {1}", x, z);
|
Операторы увеличения и уменьшения
Поддерживаются сочетания клавиш в стиле языков C/C++, включая постфиксные и префиксные операторы, как показано в следующих примерах.
Оператор | Назначение |
v++ | Увеличение переменной v на 1. |
v+=n | Увеличение переменной v на n. |
v*=n | Умножение переменной v на n. |
v-=n | Вычитание n из переменной v. |
Пример
int x = 0;
int y = x++; // x is 1, y is 0
System.Console.WriteLine("{0} {1}", x, y);
int z = ++x; // x is 2, z is 2
System.Console.WriteLine("{0} {1}", x, z);
Relational operators
The following operators compare two values and return a bool result:
Operator | Purpose |
== | Checks for equality. |
!= | Checks for inequality. |
> | Greater than. |
< | Less than. |
>= | Greater than or equal to. |
<= | Less than or equal to. |
Example
int x = int.Parse(System.Console.ReadLine());
if (x > 100) { System.Console.WriteLine("X is greater than 100"); } |
Реляционные операторы
Следующие операторы сравнивают два значения и возвращают логический результат.
Оператор | Назначение |
== | Проверка на равенство. |
!= | Проверка на неравенство. |
> | Больше. |
< | Меньше. |
>= | Больше или равно. |
<= | Меньше или равно. |
Пример
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());
}
}
- Введение в язык c# и .Net Framework
- Язык c#
- Архитектура платформы .Net Framework
- Creating Your First c# Application
- To create a c# application
- Создание первого приложенияC#
- Создание приложения c#
- To create a c# console application
- Создание консольного приложения c#
- To create a c# Windows application
- Создание приложений Windows Forms на c#
- Introduction to Windows Presentation Foundation
- To create a wpf application
- Создание приложения wpf c#
- To create event handlers
- Создание обработчиков событий
- Designing a User Interface in Visual c#
- Adding Controls
- Создание пользовательского интерфейса в Visual c#
- Добавление элементов управления
- Setting Properties
- Handling Events
- Задание свойств
- Обработка событий
- How to: Use Button Controls
- Использование элемента управления "Button"
- To use buttons in a program
- Использование кнопок в программе
- How to: Call a Button's Click Event Programmatically
- To use buttons in a program
- Программный вызов события нажатия кнопки
- Использование кнопок в программе
- How to: Create a Group of Radio Buttons from a String Array
- Compiling the Code
- Example
- Создание группы переключателей из массива строк
- Создание непрямоугольной кнопки
- Компиляция кода
- How to: Display Text on a Windows Form
- To display text in a label
- Отображение текста в форме Windows Forms
- Отображение текста в надписи
- How to: Use TextBox Controls to Get User Input
- Использование элемента управления "TextBox" для получения вводимых данных
- To retrieve input typed in a text box
- Извлечение введенных в текстовое поле данных
- How to: Convert the Text in a TextBox Control to an Integer
- Диалоговые окна Извлечение данных из диалогового окна
- To create the main form of your application
- To create a dialog box
- Создание основной формы приложения
- Создание диалогового окна
- Retrieving Data from a Dialog Box
- To retrieve data from a dialog box.
- Извлечение данных из диалогового окна
- How to: Browse a Folder
- To display the folder browser dialog box
- Просмотр папки
- Отображение диалогового окна обозревателя папок
- How to: Save a File to a Folder
- To display the folder browser dialog box
- Сохранение файла в папку
- Отображение диалогового окна обозревателя папок
- How to: Display a List of Fonts
- To display the font dialog box
- Отображение списка шрифтов
- Отображение диалогового окна выбора шрифта
- How to: Display an OpenFileDialog Dynamically
- Отображение цветовой палитры
- Отображение диалогового окно выбора цвета
- ListBox and ComboBox Controls
- Compiling the Code
- Отображение даты и времени в приложении
- Отображение даты с помощью элемента управления "MonthCalendar"
- To display the time by using a DateTimePicker control
- Отображение времени с помощью элемента управления "DateTimePicker"
- How to: Determine the Span Between Two Dates
- Создание настраиваемого пользовательского интерфейса
- Добавление панелей инструментов в приложение Windows Forms
- To add a set of standard toolbar button
- Добавление набора стандартных кнопок панели инструментов
- How to: Create a Tooltip for a Control
- Compiling the Code
- Compiling the Code
- Добавление элементов управления Windows Forms во время выполнения
- Компиляция кода15
- Accessing and Displaying Data
- How to: Write Class Data to an xml File
- Example
- Compiling the Code
- Compiling the Code
- Robust Programming
- Чтение xml из файла
- Пример18
- Компиляция кода
- Надежное программирование
- How to: Read Class Data from an xml File
- Example
- Compiling the Code
- Robust Programming
- Чтение данных класса из xml-файла
- Пример19
- Компиляция кода
- Compiling the Code
- Компиляция кода
- Compiling the Code
- Robust Programming
- Рисование кривой в форме
- Компиляция кода
- Надежное программирование
- How to: Draw Outlined Shapes
- Example
- Compiling the Code
- Robust Programming
- Рисование контурных фигур
- Пример23
- Компиляция кода
- Добавление файлов мультимедиа в приложение
- Внедрение проигрывателя Windows Media в форму
- Добавление элемента управления "Windows Media Player" в панель элементов.
- To add the Windows Media Player control to a Windows Form
- Добавление элемента управления "Windows Media Player" в форму Windows Forms
- How to: Play Sounds in an Application
- To play an audio file
- Воспроизведение звука в приложении
- Воспроизведение аудиофайла
- Creating and Using Bitmaps and Icons
- How to: Create a Bitmap at Run Time
- Example
- Создание и использование точечных рисунков и значков
- Создание точечного рисунка во время выполнения
- Compiling the Code
- Compiling the Code
- Создание приложений wpf
- Создание пользовательского интерфейса для приложения wpf
- To create a wpf application
- Создание приложения wpf
- Adding Controls to the wpf Window You can add controls to the wpf window by dragging them from the Toolbox. To add a control to the wpf window
- Добавление элементов управления в окно wpf
- Добавление элемента управления в окно wpf
- Common wpf Controls
- Procedure To add a control to the wpf window
- Стандартные элементы управления wpf
- Процедура Добавление элемента управления в окно wpf
- Standard wpf Controls
- Стандартные элементы управления wpf
- How to: Create Event Handlers for wpf Controls
- To create an event handler for a button
- Создание обработчиков событий для элементов управления wpf
- Создание обработчика событий для кнопки
- Connecting to Data
- How to: Connect to a Database
- To add a connection to the Northwind database
- Подключение к данным
- Подключение к базе данных
- Добавление подключения к базе данных "Northwind"
- How to: Display Related Data on a Form
- To display related data on a form
- Отображение связанных данных в форме
- Отображение связанных данных в форме
- Using linq in c# Express
- Advantages of Using linq
- Использование linq в c# Express
- Преимущества использования linq
- C# Language Enhancements that Support linq
- Расширения языка c# для поддержки linq
- Writing linq Queries
- Linq to Objects
- Написание запросов linq
- Linq to Objects
- Linq to sql
- Linq to DataSet
- Linq to xml
- Linq to sql
- Linq to DataSet
- ЯзыкC# для начинающих Структура программы c#
- "Hello World" в стиле c#
- Using Directives and Namespaces
- Comments
- Директивыusingи пространства имен
- Комментарий
- Classes
- Console Input and Output
- Консольный ввод и вывод
- Program Structure and Flow of Execution
- Windows Forms Applications
- Структура программы и ход выполнения
- Приложения Windows Forms36
- Console Applications
- Namespaces
- Консольные приложения
- Пространства имен
- Namespace Shortcuts
- Creating Your Own Namespace
- Ускоренный доступ к содержимому пространства имен
- Создание собственного пространства имен
- Example
- Classes
- Classes vs. Objects
- Классы и объекты
- Static vs. Instance Members
- Classes vs. Files
- Члены экземпляра и статические члены37
- Классы и файлы
- Encapsulation
- Инкапсуляция
- Inheritance
- Polymorphism
- Наследование
- Полиморфизм
- Constructors
- Конструкторы
- Operator Overloading
- Compiling the Code
- Имитация параметров по умолчанию
- Компиляция кода
- Переменные и константы
- Constants
- Built-in Data Types
- Константы
- Встроенные типы данных
- Using Built-in Data Types
- Типы значений и ссылочные типы
- Boxing and Unboxing
- Упаковка и распаковка
- Performance issues
- Проблемы производительности
- Operators
- Decisions and Branching
- Remarks
- Выбор и ветвление
- Foreach Loops
- Циклы foreach
- For Loops
- Working with Strings
- Доступ к отдельным знакам
- Changing Case
- Смена регистра
- Comparisons
- Сравнения
- Splitting a String into Substrings
- Разделение строки на подстроки
- Using StringBuilder
- Использование класса StringBuilder
- How to: Generate Multiline String Literals
- Массивы и коллекции
- Массивы
- Одномерные массивы
- Multidimensional Arrays
- Jagged Arrays
- Многомерные массивы
- Массивы массивов
- Using the foreach Statement
- Использование оператора foreach
- Arrays of Objects
- Массивы объектов
- How to: Declare an Array
- Compiling the Code
- Robust Programming
- Инициализация массива
- Компиляция кода
- Коллекции
- How to: Iterate Through an Array
- Compiling the Code
- Компиляция кода
- Enumerations
- Перечисления
- More Advanced Enumeration Techniques
- Try and Catch
- Обработка ошибок и исключений
- Try и Catch
- Finally Blocks
- Using Exception Handling
- You can also cause your own exceptions using the throw keyword.
- Блоки finally
- How to: Catch an Exception
- Example
- Compiling the Code
- Перехват исключения
- Компиляция кода
- .Net Framework Conceptual Overview
- Общие сведения об основных понятиях платформы .Net Framework
- Features of the Common Language Runtime
- Возможности среды clr
- .Net Framework Class Library
- Библиотека классов платформы .Net Framework