Nice programing

Nullable이있는 조건부 연산자 할당

nicepro 2020. 12. 12. 12:26
반응형

Nullable이있는 조건부 연산자 할당 유형?


EmployeeNumber =
string.IsNullOrEmpty(employeeNumberTextBox.Text)
    ? null
    : Convert.ToInt32(employeeNumberTextBox.Text),

나는 종종 나 자신 (이 같은 일을하고자 찾을 수 EmployeeNumber있는 Nullable<int>그 열이 NULL 값을 허용하는 LINQ - 투 - SQL DBML 객체의 속성입니다 참조). 불행히도 컴파일러는 " 'null'과 'int'사이에 암시 적 변환이 없습니다"라고 느낍니다. 비록 두 유형이 자체적으로 nullable int에 대한 할당 작업에서 유효하더라도.

Null 병합 연산자는 null이 아닌 경우 .Text 문자열에서 발생해야하는 인라인 변환 때문에 내가 볼 수있는 한 옵션이 아닙니다.

내가 아는 유일한 방법은 if ​​문을 사용하거나 두 단계로 할당하는 것입니다. 이 특별한 경우에는 객체 이니셜 라이저 구문을 사용하고 싶었고이 할당이 초기화 블록에 있기 때문에 매우 실망 스럽습니다.

누구든지 더 우아한 솔루션을 알고 있습니까?


조건부 연산자가 표현식의 유형을 결정하기 위해 값이 사용되는 방식 (이 경우 할당 됨)을 보지 않기 때문에 문제가 발생합니다. 참 / 거짓 값만 있습니다. 이 경우 nullInt32 가 있고 형식을 결정할 수 없습니다 (실제로 Nullable <Int32> 가정 할 수없는 이유가 있습니다 ).

이 방법으로 실제로 사용하려면 값 중 하나를 Nullable <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;

EDIT: Brief explanation of above, I was trying to get the value of Posid (if its nonnull int and having value greater than 0) in varibale X1. I had to use (int?) on Posid.Value to get the conditional operator not throwing any compilation error. Just a FYI GetHolidayCount is a WCF method that could give null or any number. Hope that helps

참고URL : https://stackoverflow.com/questions/75746/conditional-operator-assignment-with-nullablevalue-types

반응형