小编典典

string.IsNullOrEmpty(string)与string.IsNullOrWhiteSpace(string)

c#

在.NET
4.0及更高版本中string.IsNullOrEmpty(string)检查字符串时,使用是否被视为不好的做法string.IsNullOrWhiteSpace(string)


阅读 422

收藏
2020-05-19

共1个答案

小编典典

最佳做法是选择最合适的一种。

.Net Framework 4.0 Beta
2为字符串提供了一个新的IsNullOrWhiteSpace()方法,该方法将IsNullOrEmpty()方法推广为除空字符串之外还包括其他空白。

术语“空白”包括屏幕上不可见的所有字符。 例如,空格,换行符,制表符和空字符串是空格字符*。

参考:这里

对于性能而言,IsNullOrWhiteSpace并不理想,但很好。该方法调用将导致较小的性能损失。此外,如果您不使用Unicode数据,则IsWhiteSpace方法本身具有一些可以删除的间接寻址。与往常一样,过早的优化可能是邪恶的,但这也很有趣。

参考:这里

检查源代码 (参考源.NET Framework 4.6.2)

IsNullorEmpty

[Pure]
public static bool IsNullOrEmpty(String value) {
    return (value == null || value.Length == 0);
}

IsNullOrWhiteSpace

[Pure]
public static bool IsNullOrWhiteSpace(String value) {
    if (value == null) return true;

    for(int i = 0; i < value.Length; i++) {
        if(!Char.IsWhiteSpace(value[i])) return false;
    }

    return true;
}

例子

string nullString = null;
string emptyString = "";
string whitespaceString = "    ";
string nonEmptyString = "abc123";

bool result;

result = String.IsNullOrEmpty(nullString);            // true
result = String.IsNullOrEmpty(emptyString);           // true
result = String.IsNullOrEmpty(whitespaceString);      // false
result = String.IsNullOrEmpty(nonEmptyString);        // false

result = String.IsNullOrWhiteSpace(nullString);       // true
result = String.IsNullOrWhiteSpace(emptyString);      // true
result = String.IsNullOrWhiteSpace(whitespaceString); // true
result = String.IsNullOrWhiteSpace(nonEmptyString);   // false
2020-05-19