2012-01-17 10 views
6

C#의 null 병합 연산자 (??)에 대한 다음 내용을 이해합니다.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로 to Case II에서 오류를 보여줍니다. 'Error 1 암시 적으로'int 유형을 변환 할 수 없습니까? ' 'INT' "

에 내가 널 병합 연산자에 대해 실종 오전? 관심을

감사합니다.

답변

5

이 삼항 연산자와 두 번째 경우 작동하게하려면, 당신은을 사용할 수 그것을 무엇입니까 다음.

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

Nullable<T> 유형의 Value 속성은 T 값을 반환합니다 (이 경우, int를)

또 다른 옵션은 Nullable<T>.HasValue을 사용하는 것입니다

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

myNullableInt != null 구조는 위의 HasValue 전화 만 문법 설탕입니다.

+0

첫 번째 테스트가 사용해야 '='보다는 '=='보다 – hvd

+0

@hvd! 물론 올바른 I 나쁜 예 데 대한 OP 비난. : - P 편집 됨. –

+0

사실, 당신의 대답이 약간 벗어난 것 같아요. b : c', 여기서'b'는'int'이고'c'는'int'입니다. 그러나 결과에는'int? '유형이 있으므로'(a? b : c) .Value'가 필요합니다. 또는 귀하의 제안 된 수정,에 대한 자리입니다. – hvd

5

널 통합 연산자 ??에 대해 관찰 한이 동작은 문서화 된 언어 기능입니다. 자세한 내용은 C# 4.0 언어 사양 섹션 7.13을 참조하십시오.

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.

조건 연산자 a ? b : c이 다르게 작동하는 이유는 7.14 절을 참조하십시오.

Download the specification 귀하의 여가에 따라 완벽하게 읽을 수 있습니다. 삼항 연산자와 함께 사용하기에 두 가지 유형이 정확히 동일해야하기 때문에 이것은 (컴파일되지 않습니다 이제

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

: 당신은 아마 의미 -

0
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