반응형
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
반응형
'Program Tip' 카테고리의 다른 글
속성의 존재를 확인하는 가장 좋은 방법은 무엇입니까? (0) | 2020.11.26 |
---|---|
NodeJS 요청의 모듈 gzip 응답 본문을 어떻게 ungzip (압축 해제)합니까? (0) | 2020.11.26 |
사전이 목록보다 훨씬 빠른 이유는 무엇입니까? (0) | 2020.11.26 |
모델을 통해 입력 자리 표시 자의 값을 변경 하시겠습니까? (0) | 2020.11.26 |
파이썬에서 for 루프 피라미드를 더 간결하게 만들려면 어떻게해야합니까? (0) | 2020.11.26 |