使用 string.isnullorwhitespace() 方法可以判断字符串是否为 null、空字符串或仅包含空白字符。该方法内部会检查引用是否为 null,长度是否为零,以及是否只由空格、制表符等不可见字符组成。

IsNullOrWhiteSpace 处理 null 和空字符串的逻辑是什么
当输入为 null 时直接返回 true;当输入为空字符串时,由于长度为 0,循环不执行,也返回 true。这避免了在调用前进行额外的 null 检查。

using System;
public class Program {
public static void Main() {
string s1 = null;
string s2 = "";
Console.WriteLine(string.IsNullOrWhiteSpace(s1)); // True
Console.WriteLine(string.IsNullOrWhiteSpace(s2)); // True
}
}
IsNullOrWhiteSpace 如何识别纯空格字符串
对于非 null 且非空的字符串,该方法会遍历每个字符,如果所有字符都是空白字符(如空格 ' '、制表符 '\t'、换行 '\n'),则返回 true。只要有一个非空白字符,立即返回 false。

using System;
public class Program {
public static void Main() {
string s3 = " ";
string s4 = " a ";
Console.WriteLine(string.IsNullOrWhiteSpace(s3)); // True
Console.WriteLine(string.IsNullOrWhiteSpace(s4)); // False
}
}
为什么 Trim().Length == 0 不如 IsNullOrWhiteSpace 安全
如果使用 str.Trim().Length == 0,当 str 为 null 时会抛出 NullReferenceException。而 IsNullOrWhiteSpace 是静态方法,内置了 null 检查,更加健壮。











