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

Явные преобразования

Допускающий значение null тип может быть приведен к обычному типу либо явным образом с помощью приведения, либо с помощью свойства Value. Например:

int? n = null;

//int m1 = n; // Will not compile.

int m2 = (int)n; // Compiles, but will create an exception if x is null.

int m3 = n.Value; // Compiles, but will create an exception if x is null.

Если определенное пользователем преобразование определено между двумя типами данных, то это же преобразование может быть также использовано с допускающими значение null версиями этих типов данных.

Неявные преобразования

Переменной допускающего значение null типа может быть присвоено значение null с помощью ключевого слова null, как показано в следующем примере:

int? n1 = null;

Преобразование из обычного типа в допускающий значение null тип является неявным.

int? n2;

n2 = 10; // Implicit conversion.

Operators

The predefined unary and binary operators and any user-defined operators that exist for value types may also be used by nullable types. These operators produce a null value if the operands are null; otherwise, the operator uses the contained value to calculate the result. For example:

int? a = 10;

int? b = null;

a++; // Increment by 1, now a is 11.

a = a * 10; // Multiply by 10, now a is 110.

a = a + b; // Add b, now a is null.

When performing comparisons with nullable types, if one of the nullable types is null, the comparison is always evaluated to be false. It is therefore important not to assume that because a comparison is false, the opposite case is true. For example:

int? num1 = 10;

int? num2 = null;

if (num1 >= num2)

{

System.Console.WriteLine("num1 is greater than or equal to num1");

}

else

{

// num1 is NOT less than num2

}

The conclusion in the else statement is not valid because num2 is null and therefore does not contain a value.

A comparison of two nullable types which are both null will be evaluated to true.

Операторы

Существующие для типов значений предварительно определенные унарные и бинарные операторы, а также определенные пользователем операторы могут также использоваться допускающими значение null типами. Эти операторы создают значение null, если операнды имеют значение null; иначе оператор использует для вычисления результата содержащееся значение. Например:

---

Если при выполнении сравнения с допускающими значение null типами один из допускающих значение null типов содержит null, то результатом сравнения всегда является false. Следовательно, важно не считать, что если результатом сравнения является false, то противоположным случаем является true. Например:

int? num1 = 10;

int? num2 = null;

if (num1 >= num2)

{

System.Console.WriteLine("num1 is greater than or equal to num1");

}

else

{

// num1 is NOT less than num2

}

Комментарий, написанный после else является не верным, потому что num2 содержит null и, следовательно, не содержит какого-либо значения.

Сравнение двух допускающих значение null типов, оба из которых содержат null, будет давать результат true.

The ?? Operator

The ?? operator defines a default value that is returned when a nullable type is assigned to a non-nullable type.

int? c = null;

// d = c, unless c is null, in which case d = -1.

int d = c ?? -1;

This operator can also be used with multiple nullable types. For example:

int? e = null;

int? f = null;

// g = e or f, unless e and f are both null, in which case g = -1.

int g = e ?? f ?? -1;

The bool? type

The bool? nullable type can contain three different values: true, false and null.

Nullable Booleans are like the Boolean variable type that is used in SQL. To ensure that the results produced by the & and | operators are consistent with the three-valued Boolean type in SQL, the following predefined operators are provided:

bool? operator &(bool? x, bool? y)

bool? operator |(bool? x, bool? y)

The results of these operators are listed in the following table: