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

Упаковка и распаковка

Упаковкой называется процесс преобразования типа значения в ссылочный тип. Для упаковки переменной необходимо создать ссылочную переменную, указывающую на новую копию в куче. Распаковка применяется для классов, предназначенных для работы с объектами: например, использование ArrayList для хранения целых чисел. Для хранения целых чисел в ArrayList используется упаковка. При извлечении целого числа должна быть применена распаковка.

System.Collections.ArrayList list =

new System.Collections.ArrayList(); // list есть ссылочный тип

int n = 67; // n относится к типу-значению

list.Add(n); // n упаковывается

n = (int)list[0]; // list[0] распаковывается

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

}

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