Program Tip

If string is not null or empty else에 대한 라이너 1 개

programtip 2020. 11. 26. 19:47
반응형

If string is not null or empty else에 대한 라이너 1 개


나는 일반적으로 응용 프로그램 전체에서 다양한 이유로 다음과 같은 것을 사용합니다.

if (String.IsNullOrEmpty(strFoo))
{
     FooTextBox.Text = "0";
}
else
{
     FooTextBox.Text = strFoo;
}

많이 사용하려면 원하는 문자열을 반환하는 메서드를 만듭니다. 예를 들면 :

public string NonBlankValueOf(string strTestString)
{
    if (String.IsNullOrEmpty(strTestString))
        return "0";
    else
        return strTestString;
}

다음과 같이 사용하십시오.

FooTextBox.Text = NonBlankValueOf(strFoo);

나는 항상 나를 위해 이것을 할 C #의 일부인 것이 있는지 궁금했습니다. 다음과 같이 부를 수있는 것 :

FooTextBox.Text = String.IsNullOrEmpty(strFoo,"0")

두 번째 매개 변수는 String.IsNullOrEmpty(strFoo) == true

아무도 그들이 사용하는 더 나은 접근 방식이 없다면?


null 병합 연산자 ( ??)가 있지만 빈 문자열을 처리하지 않습니다.

널 문자열 처리에만 관심이 있다면 다음과 같이 사용합니다.

string output = somePossiblyNullString ?? "0";

특별히 필요에 따라 bool expr ? true_value : false_value단순히 값을 설정하거나 반환하는 if / else 문 블록에 사용할 수 있는 조건부 연산자 가 있습니다.

string output = string.IsNullOrEmpty(someString) ? "0" : someString;

삼항 연산자를 사용할 수 있습니다 .

return string.IsNullOrEmpty(strTestString) ? "0" : strTestString

FooTextBox.Text = string.IsNullOrEmpty(strFoo) ? "0" : strFoo;

String 유형에 대한 자체 확장 메서드를 작성할 수 있습니다 .

 public static string NonBlankValueOf(this string source)
 {
    return (string.IsNullOrEmpty(source)) ? "0" : source;
 }

이제 모든 문자열 유형과 같이 사용할 수 있습니다.

FooTextBox.Text = strFoo.NonBlankValueOf();

도움이 될 수 있습니다.

public string NonBlankValueOf(string strTestString)
{
    return String.IsNullOrEmpty(strTestString)? "0": strTestString;
}

오래된 질문이지만 도움을주기 위해 이것을 추가 할 것이라고 생각했습니다.

#if DOTNET35
bool isTrulyEmpty = String.IsNullOrEmpty(s) || s.Trim().Length == 0;
#else
bool isTrulyEmpty = String.IsNullOrWhiteSpace(s) ;
#endif

참고 URL : https://stackoverflow.com/questions/15660461/one-liner-for-if-string-is-not-null-or-empty-else

반응형