2010-06-11 3 views
0

가능한 중복 : 예를 들어
Nullable types and the ternary operator. Why won’t this work?C# nullable 형식의 질문

:

int? taxid; 
if (ddlProductTax.SelectedValue == "") { 
    taxid = null; } 
else { 
    taxid = Convert.ToInt32(ddlProductTax.SelectedValue); 
} //Correct 

그러나

int? taxid; 
taxid = (ddlProductTax.SelectedValue == "" ? null : Convert.ToInt32(ddlProductTax.SelectedValue)); //Error 

오류가 발생했으며 int32는 암시 적 변환을 할 수 없습니다.

(? truepart : falsepart); ... (만약 ..) .. 부족하다?

+0

@Gishu, 정확한 내가 말하고 싶지만 중복. @TatMing은 연결된 복제물에 대한 응답을 확인합니다. – Paolo

+0

에릭 리 퍼트 (Eric Lippert)가 최근 블로그 게시물 [http://blogs.msdn.com/b/ericlippert/archive/2010/05/27/cast-operators-do-not-obey-the-distributive-law. aspx] (http://blogs.msdn.com/b/ericlippert/archive/2010/05/27/cast-operators-do-not-obey-the-distributive-law.aspx) – benPearce

답변

4

3 진 연산자의 마지막 두 피연산자는 모두 동일한 유형을 가져야합니다.

캐스트 양쪽 int?에 :

taxid = ddlProductTax.SelectedValue == "" ? 
           (int?)null 
           : Convert.ToInt32(ddlProductTax.SelectedValue); 

당신은 사양에서 정확한 동작을 볼 수

0

이 보정을 적용하고 그것을 작동합니다.

int? taxid; 
taxid = (ddlProductTax.SelectedValue == "" ? null : new int?(Convert.ToInt32(ddlProductTax.SelectedValue))); //Now it works. 
0

는 여기에 내가 그것을 표현을 평가하는 방법으로 아래의 생각 약간의 도우미 메서드

taxid = GetNullableInt32(ddlProductTax.SelectedValue); 

public static int? GetNullableInt32(string str) 
{ 
     int result; 
     if (Int32.TryParse(str, out result)) 
     { 
      return result; 
     } 
     return null; 
} 
0

입니다. ? : 구문을 사용하면 두 결과가 동일한 유형으로 추출되어야하며 여기에서 null 값과 Int32 사이의 암시 적 변환은 없습니다.

시도 :

taxid = (ddlProductTax.SelectedValue == "")? Convert.ToInt32(null) : Convert.ToInt32(ddlProductTax.SelectedValue);