2009-08-14 3 views
59

가능한 복제를 int로하지 :
Nullable types and the ternary operator: why is `? 10 : null` forbidden?C# 코드가 컴파일되지 않습니다. 널 (null)와 사이에 암시 적 변환은

하지 않는 이유는이 작품? 유효한 코드와 같습니다.

string cert = ddCovCert.SelectedValue; 
    int? x = (string.IsNullOrEmpty(cert)) ? null: int.Parse(cert); 
    Display(x); 

어떻게 코딩해야합니까? 이 메서드는 Nullable을 사용합니다. 드롭 다운이 선택된 문자열을 가지고 있다면 int로 해석해야합니다. 그렇지 않으면 메소드에 null을 전달하려고합니다. 내가 같은 일에 걸쳐 왔어요

+4

복제를 (INT?) - http://stackoverflow.com/questions/858080를 참조하십시오/nullable-types-and-the-ternary-operator-why-wake-this-work –

+1

자세한 내용은 http://stackoverflow.com/questions/220250/in-c-why-canta-a-를 참조하십시오. 조건부 - 연산자 - 암시 적으로 캐스트 - nullable-type –

답변

195
int? x = string.IsNullOrEmpty(cert) ? (int?)null : int.Parse(cert); 
+0

아름답다. 감사! – Hcabnettek

+0

가끔은 필요하지만, 항상 잊어 버리고 끝납니다 : D. 감사합니다 – Steven

+0

내 시간을 절약했습니다. 감사 . –

7

... 난 보통 단지에 널 캐스팅

int? x = (string.IsNullOrEmpty(cert)) ? (int?)null: int.Parse(cert);