programing

Why can't I set a nullable int to null in a ternary if statement?

telebox 2023. 7. 31. 21:18
반응형

Why can't I set a nullable int to null in a ternary if statement?

The C# code below:

int? i;
i = (true ? null : 0);

gives me the error:

Type of conditional expression cannot be determined because there is no implicit conversion between '<null>' and 'int'

Shouldn't this be valid? What am i missing here?

컴파일러가 오른쪽 식을 평가하려고 합니다.null이라null그리고0이다.int문자 그대로가 아닌int?컴파일러가 식을 어떤 유형으로 평가해야 하는지 결정할 수 없다고 알려주려고 합니다.사이에는 암묵적인 변환이 없습니다.null그리고.int따라서 오류 메시지가 표시됩니다.

당신은 컴파일러에게 표현식이 다음과 같이 평가되어야 한다고 말할 필요가 있습니다.int?사이에 암묵적인 변환이 있습니다.int?그리고.int또는 그 사이에null그리고.int?따라서 다음 중 하나가 작동해야 합니다.

int? x = true ? (int?)null : 0;

int? y = true ? null : (int?)0;

You need to use the default() keyword rather than null when dealing with ternary operators.

Example:

int? i = (true ? default(int?) : 0);

Alternately, you could just cast the null:

int? i = (true ? (int?)null : 0);

개인적으로 저는 그 일을 고수합니다.default()표기법, 그건 그냥 선호일 뿐이야, 정말.하지만 궁극적으로 IMHO라는 특정한 표기법을 고수해야 합니다.

HTH!

그 부분(true ? null : 0)어떤 면에서는 함수가 됩니다.이 함수에는 반환 형식이 필요합니다.컴파일러가 반환 유형을 파악해야 할 때는 파악할 수 없습니다.

This works:

int? i;
i = (true ? null : (int?)0);

ReferenceURL : https://stackoverflow.com/questions/2766932/why-cant-i-set-a-nullable-int-to-null-in-a-ternary-if-statement

반응형