string.IsNullOrEmpty 和 IsNullOrWhiteSpace 这两个方法的区别和用法
IsNullOrEmpty
public static bool IsNullOrEmpty(string? value)
这个方法检查字符串是否为:
1. null
2. 空字符串 ("")
string str1 = null;
string str2 = "";
string str3 = " ";
Console.WriteLine(string.IsNullOrEmpty(str1)); // true
Console.WriteLine(string.IsNullOrEmpty(str2)); // true
Console.WriteLine(string.IsNullOrEmpty(str3)); // false
IsNullOrWhiteSpace
public static bool IsNullOrWhiteSpace(string? value)
这个方法检查字符串是否为:
1. null
2. 空字符串 ("")
3. 只包含空白字符的字符串(空格、制表符、换行符等)
string str1 = null;
string str2 = "";
string str3 = " ";
string str4 = "\t\n\r";
string str5 = " "; // 包含全角空格
Console.WriteLine(string.IsNullOrWhiteSpace(str1)); // true
Console.WriteLine(string.IsNullOrWhiteSpace(str2)); // true
Console.WriteLine(string.IsNullOrWhiteSpace(str3)); // true
Console.WriteLine(string.IsNullOrWhiteSpace(str4)); // true
Console.WriteLine(string.IsNullOrWhiteSpace(str5)); // true
主要区别
检查范围 :
- IsNullOrEmpty 只检查 null 和空字符串
- IsNullOrWhiteSpace 还会检查空白字符
性能 :
- IsNullOrEmpty 性能略好,因为不需要遍历字符串
- IsNullOrWhiteSpace 需要遍历字符串来检查空白字符
使用场景 :
- IsNullOrEmpty 适用于只需要检查字符串是否为空的场景
- IsNullOrWhiteSpace 适用于需要验证用户输入或数据清理的场景
使用建议
- 如果只需要检查字符串是否为 null 或空,使用 IsNullOrEmpty
- 如果需要验证用户输入,建议使用 IsNullOrWhiteSpace
- 在性能敏感的场景,优先考虑 IsNullOrEmpty
- 处理用户界面或数据验证时,优先考虑 IsNullOrWhiteSpace
注意事项
- 两个方法都是静态方法,需要通过 string. 来调用
- 从 C# 8.0 开始,这两个方法支持可空引用类型
- 这两个方法都是线程安全的
- 在处理大量数据时,性能差异可能会变得明显