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

Performance issues

Let's dig a little deeper. When data is passed into methods as value type parameters, a copy of each parameter is created on the stack. Clearly, if the parameter in question is a large data type, such as a user-defined structure with many elements, or the method is executed many times, this may have an impact on performance.

In these situations it may be preferable to pass a reference to the type, using the ref keyword. This is the C# equivalent of the C++ technique of passing a pointer to a variable into a function. As with the C++ version, the method has the ability to change the contents of the variable, which may not always be safe. The programmer needs to decide on the trade-off between security and performance.

int AddTen(int number) // parameter is passed by value

{

return number + 10;

}

void AddTen(ref int number) // parameter is passed by reference

{

number += 10;

}

The out keyword is similar to the ref keyword, but it tells the compiler that the method must assign a value to the parameter, or a compilation error will occur.

void SetToTen(out int number)

{

// If this line is not present, the code will not compile.

number = 10;

}

Проблемы производительности

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

В таких ситуациях рекомендуется передавать ссылку на тип, используя ключевое слово ref. Метод имеет возможность изменить содержимое переменной, что не всегда может быть безопасным. Программист должен находить компромиссное соотношение между безопасностью и производительностью.

int AddTen(int number) // параметр передается по значению

{

return number + 10;

}

void AddTen(ref int number) // параметр передается по ссылке

{

number += 10;

}

Ключевое слово out имеет сходство с ключевым словом ref, но оно указывает компилятору, что метод должен присвоить значение параметру, иначе возникнет ошибка компиляции.

void SetToTen(out int number)

{

// Если такая строка отсутствует, код не будет компилироваться.

number = 10;

}

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());

}

}