2012-01-17 4 views
6

Со следующего представления о нулевом коалесцирующем операторе (??) в C#.Неявное литье результата оператора Null-Coalescing

int? input = -10; 
int result = input ?? 10;//Case - I 
//is same as: 
int result = input == null? input : 10; // Case - II 

Хотя по определению и использованию случаи I и II являются одинаковыми.

Удивительно, что в случае компилятора Case-I возможно неявное литирование int? int, а в Case-II - ошибка: «Ошибка 1 Не может неявно преобразовать тип« int »? к «междам»»

Что это такое, что я пропускаю о операторе нуль-коалесцирующем?

Спасибо за ваш интерес.

ответ

5

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

int result = input != null ? input.Value : 10; 

Value свойство Nullable<T> типа возвращает значение T (в данном случае, в int)

Другой вариант заключается в использовании Nullable<T>.HasValue:

int result = input.HasValue ? input.Value : 10; 

myNullableInt != null конструкция является лишь синтаксический сахар для вышеприведенного HasValue вызова.

+0

Первое испытание следует использовать '=' вместо '' == – hvd

+0

@hvd: Совершенно верно, я виню ОП за то, что плохой пример. :-P Отредактировано. –

+0

На самом деле, я думаю, что ваш ответ немного выключен ... 'a? b: c', где 'b' является' int? 'и' c' является 'int', является абсолютно допустимым. Однако результат имеет тип 'int?', Поэтому вам понадобится '(a? B: c) .Value'. Или ваша предложенная коррекция, которая находится на месте. – hvd

5

Это поведение, которое вы наблюдали за оператором с нулевым коалесцированием ??, является документированной языковой функцией, см. Раздел 7.13 Спецификации языка C# 4.0 для более подробной информации.

The type of the expression a ?? b depends on which implicit conversions are available on the operands. In order of preference, the type of a ?? b is A0, A, or B, where A is the type of a (provided that a has a type), B is the type of b (provided that b has a type), and A0 is the underlying type of A if A is a nullable type, or A otherwise. Specifically, a ?? b is processed as follows:

  • If A exists and is not a nullable type or a reference type, a compile-time error occurs.

  • If b is a dynamic expression, the result type is dynamic. At run-time, a is first evaluated. If a is not null, a is converted to dynamic, and this becomes the result. Otherwise, b is evaluated, and this becomes the result.

  • Otherwise, if A exists and is a nullable type and an implicit conversion exists from b to A0, the result type is A0. At run-time, a is first evaluated. If a is not null, a is unwrapped to type A0, and this becomes the result. Otherwise, b is evaluated and converted to type A0, and this becomes the result.

  • Otherwise, if A exists and an implicit conversion exists from b to A, the result type is A. At run-time, a is first evaluated. If a is not null, a becomes the result. Otherwise, b is evaluated and converted to type A, and this becomes the result.

  • Otherwise, if b has a type B and an implicit conversion exists from a to B, the result type is B. At run-time, a is first evaluated. If a is not null, a is unwrapped to type A0 (if A exists and is nullable) and converted to type B, and this becomes the result. Otherwise, b is evaluated and becomes the result.

  • Otherwise, a and b are incompatible, and a compile-time error occurs.

можно найти в разделе 7,14, почему условный оператор a ? b : c работает по-другому.

Download the specification читать как полноту на досуге.

0
int result = input == null ? input : 10; 

Вы получили ваше состояние смешивается во втором случае - вы, вероятно, имел в виду:

int result = input != null ? input : 10; 

Теперь это не будет компилироваться, так как оба типа в использовании с тройной оператор должен быть абсолютно идентичным (и int? не то же самое, как int) - вы можете использовать простой бросок в виде раствора:

int result = input != null ? (int)input : 10; 
-1

Более краткий explantion:

int? NULL_Int = 1; 
int NORM_Int = 2; 

NULL_Int = NORM_Int; // OK 

NORM_Int = NULL_Int; // NO, you can't assign a null to an int 
Смежные вопросы