string.isnullorempty()不能识别只包含空格的字符串,它仅检查引用是否为 null 或长度是否为 0。要判断包含空格的字符串是否为空,应使用 string.isnullorwhitespace()。

IsNullOrEmpty 对空格串的处理逻辑是什么
IsNullOrEmpty 在遇到 " " 时返回 false,因为该字符串长度大于 0 且不为 null。其内部逻辑仅涉及两个条件:引用非空且长度非零。

using System;
class Program {
static void Main() {
string s = " ";
Console.WriteLine(string.IsNullOrEmpty(s)); // False
Console.WriteLine(s.Length); // 3
}
}
IsNullOrWhiteSpace 如何正确检测空白字符串
IsNullOrWhiteSpace 会遍历字符串中的每个字符,若所有字符均为空白字符(如空格、制表符、换行等)或字符串为 null,则返回 true。这是处理用户输入时的推荐做法。

using System;
class Program {
static void Main() {
string s = " ";
Console.WriteLine(string.IsNullOrWhiteSpace(s)); // True
Console.WriteLine(string.IsNullOrEmpty(s)); // False
}
}
当输入为 "\t\n" 时,IsNullOrWhiteSpace 的返回值是多少
当输入为 "\t\n" 时,IsNullOrWhiteSpace 返回 true,因为制表符和换行符均属于空白字符范畴。











