为什么 string.IsNullOrWhiteSpace("\0") 是错误的

Why string.IsNullOrWhiteSpace("\0") is false

我遇到了一个问题,其中不可见字符 [=11=] 很像 'white space' 不被 string.IsNullOrWhiteSpace 方法视为白色 space。我想知道为什么这在 .NET 中以这种方式实现,是否有 string.IsNullOrWhiteSpace 的替代方法可以正确处理空终止字符? 提前致谢。

U+0000 基本上不是空格。 char.IsWhitespace('[=10=]') returns 错误,它没有列为空格...

IsNullOrWhitespacenull 部分指的是字符串引用本身 - 而不是内容,如果您正在考虑的话。

请注意,出于互操作目的,.NET 中的字符串逻辑上 "null-terminated" 不在托管代码中,尽管实际上在 CLR 级别它们是。 (字符串知道自己的长度,但为了更容易使用 确实 期望空终止符的本机代码,CLR 确保在内容之后始终有一个 U+0000的字符串。)如果你最终得到一个包含 [=12=] 的字符串,你应该修复它的开头。

您可以将所有 [=11=] 字符替换为 space 字符,然后检查白色space。

string.IsNullOrWhiteSpace("[=10=]".Replace('[=10=]', ' ');

NULL 字符串不同于空字符串或白色 space

创建一个扩展方法,添加空字符作为检查。

public bool IsNullOrWhitespaceOrHasNullChar(this string text)
{
   return string.IsNullOrWhiteSpace(text) || Regex.IsMatch(text, "[=10=]");
}

请注意,空字符存在于字符串中的任何位置,它会被发现并报告为空字符,因此带有 "a[=16=]" 的字符串将 return 为真。如果这是一个问题,请创建一个测试来检查 [=11=].

的完整字符串

出于有趣的历史原因(它们肯定很有趣,但我找不到它们),null 有两个含义... null pointer/reference(称为NULL in C), NUL (or NULL) [=15=] 字符.

String.IsNullOrWhiteSpace 是:

Indicates whether a specified string is null, empty, or consists only of white-space characters.

with null表示“null引用”,empty表示空,white-space表示

White-space characters are defined by the Unicode standard. The IsNullOrWhiteSpace method interprets any character that returns a value of true when it is passed to the Char.IsWhiteSpace method as a white-space character.

Char.IsWhiteSpace 认为 space 的字符列表出现在 Char.IsWhiteSpace 的页面中。

'\0'字符不被认为是白色space。有关被视为白色的字符列表,请参阅 Char.IsWhitespace() space。

如果您有自己的要求,甚至只是添加一些您自己的字符,请使用 Enumerable.All()。像这样:

bool IsMyKindOfWhiteSpace(string input)
{
    char[] more = new char[] { <here goes your list of additional white space chars> };

    return input.All(x => Char.IsWhiteSpace(x) || more.Contains(x));
}