Nullable<value> 유형을 사용한 조건부 연산자 할당?
-
09-06-2019 - |
문제
EmployeeNumber =
string.IsNullOrEmpty(employeeNumberTextBox.Text)
? null
: Convert.ToInt32(employeeNumberTextBox.Text),
나는 종종 이런 일을 하고 싶어진다.EmployeeNumber
는 Nullable<int>
열이 NULL 값을 허용하는 LINQ-to-SQL dbml 개체의 속성이기 때문입니다.불행하게도 컴파일러는 "'null'과 'int' 사이에 암시적 변환이 없습니다"라고 생각합니다. 두 유형 모두 자체적으로 nullable int에 대한 할당 작업에서 유효하더라도 마찬가지입니다.
Null 병합 연산자는 null이 아닌 경우 .Text 문자열에서 발생해야 하는 인라인 변환으로 인해 내가 볼 수 있는 한 옵션이 아닙니다.
내가 아는 한 이를 수행하는 유일한 방법은 if 문을 사용하거나 두 단계로 할당하는 것입니다.이 특별한 경우에는 개체 초기화 구문을 사용하고 싶었고 이 할당이 초기화 블록에 있기 때문에 매우 실망스러웠습니다...
더 우아한 솔루션을 아는 사람이 있습니까?
해결책
문제는 조건부 연산자가 표현식의 유형을 결정하기 위해 값이 어떻게 사용되는지(이 경우 할당됨)를 보지 않고 단지 true/false 값만 확인하기 때문에 발생합니다.이 경우에는 없는 그리고 Int32, 유형을 결정할 수 없습니다(단순히 가정할 수 없는 실제 이유가 있습니다). Null 가능<Int32>).
실제로 이런 방식으로 사용하려면 값 중 하나를 캐스팅해야 합니다. Null 가능<Int32> C#에서 형식을 확인할 수 있습니다.
EmployeeNumber =
string.IsNullOrEmpty(employeeNumberTextBox.Text)
? (int?)null
: Convert.ToInt32(employeeNumberTextBox.Text),
또는
EmployeeNumber =
string.IsNullOrEmpty(employeeNumberTextBox.Text)
? null
: (int?)Convert.ToInt32(employeeNumberTextBox.Text),
다른 팁
나는 유틸리티 방법이 이것을 더 깨끗하게 만드는 데 도움이 될 수 있다고 생각합니다.
public static class Convert
{
public static T? To<T>(string value, Converter<string, T> converter) where T: struct
{
return string.IsNullOrEmpty(value) ? null : (T?)converter(value);
}
}
그 다음에
EmployeeNumber = Convert.To<int>(employeeNumberTextBox.Text, Int32.Parse);
Alex가 귀하의 질문에 정확하고 근접한 답변을 제공하는 동안 저는 다음을 선호합니다. TryParse
:
int value;
int? EmployeeNumber = int.TryParse(employeeNumberTextBox.Text, out value)
? (int?)value
: null;
더 안전하며 잘못된 입력 사례와 빈 문자열 시나리오를 처리합니다.그렇지 않으면 사용자가 다음과 같은 것을 입력하면 1b
처리되지 않은 예외가 발생한 오류 페이지가 표시됩니다. Convert.ToInt32(string)
.
Convert의 출력을 캐스팅할 수 있습니다.
EmployeeNumber = string.IsNullOrEmpty(employeeNumberTextBox.Text)
? null
: (int?)Convert.ToInt32(employeeNumberTextBox.Text)
//Some operation to populate Posid.I am not interested in zero or null
int? Posid = SvcClient.GetHolidayCount(xDateFrom.Value.Date,xDateTo.Value.Date).Response;
var x1 = (Posid.HasValue && Posid.Value > 0) ? (int?)Posid.Value : null;
편집하다:위의 간략한 설명, 나는 Posid
(null이 아닌 경우 int
0보다 큰 값을 가짐) X1
.나는 사용해야했다 (int?)
~에 Posid.Value
조건부 연산자가 컴파일 오류를 발생시키지 않도록 합니다.참고로 말씀드리자면 GetHolidayCount
는 WCF
줄 수 있는 방법 null
또는 임의의 숫자.도움이 되었기를 바랍니다