String.ISNULLOREMPTY 사용 트림 ()
-
14-12-2019 - |
문제
첫 번째 줄을 제거하고 싶습니다 :
!string.IsNullOrEmpty(cell.Text)
.
이 문제가 발생합니까?
나는 몇 가지 코드에서 이것을 가로 지르도록
if ((id % 2 == 0)
&& !string.IsNullOrEmpty(cell.Text)
&& !string.IsNullOrEmpty(cell.Text.Trim())
)
.
첫 번째 string.isnullorempty가 공백이있는 문자열에서 거짓을 반환 할 것 같습니다. 그리고 TRIM ()이있는 라인은 그것을 돌 봅니다. 그래서 첫 번째 Isnullorempty는 쓸모 없게됩니다
그러나 트림없이 라인을 제거하기 전에 나는 그것을 그룹으로 실행할 것이라고 생각했습니다.
해결책
첫 번째 IsNullOrempty는 트림 ()을 사용하여 NullReferenceException을 던지기 전에 널 값을 잡습니다.
그러나 더 나은 방법이 있습니다 :
if ((id % 2 == 0) && !string.IsNullOrWhiteSpace(cell.Text))
. 다른 팁
cell.text가 null 인 경우 첫 번째 확인 없이는 예외가 있습니다.
.NET 4.0 :
if (id % 2 == 0 && !string.IsNullOrWhiteSpace(cell.Text))
{
...
}
.
이전 버전에서는 두 가지 테스트를 유지해야합니다. 첫 번째 및 cell.Text
를 제거하면 null 인스턴스에서 .Trim
를 호출하려고하면 두 번째로 NRE를 얻을 수 있습니다.
또는 이렇게 할 수도 있습니다.
if (id % 2 == 0 && string.IsNullOrWhiteSpace((cell.Text ?? string.Empty).Trim()))
{
...
}
.
또는 더 나은, 확장 방법 간단하게 다음을 수행 할 문자열 유형은 다음과 같습니다.
if (id % 2 == 0 && !cell.Text.IsNullOrWhiteSpace())
{
...
}
.
다음과 같이 보일 수 있습니다 :
public static class StringExtensions
{
public static bool IsNullOrWhiteSpace(this string value)
{
return string.IsNullOrEmpty((value ?? string.Empty).Trim());
}
}
. 테스트가 셀이 null 첫 번째가 아니라는 것을 보장하는 것이 믿습니다 ... 그렇다면 그것을 무시하고 셀을 얻으려고 노력하고 셀을 얻으려고합니다. 트림 ()은 당신이 자르기를 할 수없는 것처럼 질식 될 것입니다.null 문자열.
!string.IsNullOrWhitespace(call.Text)
를 사용하고 이전 두 검사를 사용하지 않으시겠습니까?
셀이 null 일 수 있으므로 첫 번째 isnullorempty만을 제거 할 수 없으므로 트림을 호출하면 트림이 발생합니다. isnullorwhitespace read를 사용하는 경우두 검사 모두.
if ((id % 2 == 0) && !string.IsNullOrWhiteSpace(cell.Text))
. cell.text가 null이면 reigrion.isnullorempty (cell.text.trim ())는 셀에서 메소드 트림 ()을 실행하려고 시도하기 때문에 예외를 throw합니다.
조건이있을 경우 훨씬 더 readble : cell.text!= null && cell.text.trim ()!="
다음과 같이 확장 방법을 사용할 수 있습니다.
/// <summary>
/// Indicates whether the specified string is null or empty.
/// This methods internally uses string.IsNullOrEmpty by trimming the string first which string.IsNullOrEmpty doesn't.
/// .NET's default string.IsNullOrEmpty method return false if a string is just having one blank space.
/// For such cases this custom IsNullOrEmptyWithTrim method is useful.
/// </summary>
/// <returns><c>true</c> if the string is null or empty or just having blank spaces;<c>false</c> otherwise.</returns>
public static bool IsNullOrEmptyWithTrim(this string value)
{
bool isEmpty = string.IsNullOrEmpty(value);
if (isEmpty)
{
return true;
}
return value.Trim().Length == 0;
}
.