在c#中同时判断字符串为null或空串,最直接且推荐的做法是调用 string.isnullorempty() 静态方法。该方法接收一个 string 类型的参数,当传入的引用为 null 或者其长度为0时,返回 true;否则返回 false。使用此方法可以避免手动检查 == null 和 .length == 0 带来的冗余代码,并防止对 null 对象调用属性引发的 nullreferenceexception。

IsNullOrEmpty与IsNullOrWhiteSpace的区别是什么
这两个方法都用于处理无效字符串,但判断标准不同。IsNullOrEmpty 仅检查是否为 null 或零长度(""),而 IsNullOrWhiteSpace 在此基础上还检查字符串是否仅包含空白字符(如空格、制表符、换行符)。如果业务逻辑需要忽略纯空白输入,应使用后者。

using System;
public class Program
{
public static void Main()
{
string input1 = null;
string input2 = "";
string input3 = " ";
string input4 = "hello";
Console.WriteLine("IsNullOrEmpty:");
Console.WriteLine($"null: {string.IsNullOrEmpty(input1)}"); // True
Console.WriteLine($"empty: {string.IsNullOrEmpty(input2)}"); // True
Console.WriteLine($"spaces: {string.IsNullOrEmpty(input3)}"); // False
Console.WriteLine($"text: {string.IsNullOrEmpty(input4)}"); // False
Console.WriteLine("\nIsNullOrWhiteSpace:");
Console.WriteLine($"null: {string.IsNullOrWhiteSpace(input1)}"); // True
Console.WriteLine($"empty: {string.IsNullOrWhiteSpace(input2)}"); // True
Console.WriteLine($"spaces: {string.IsNullOrWhiteSpace(input3)}"); // True
Console.WriteLine($"text: {string.IsNullOrWhiteSpace(input4)}"); // False
}
}
运行上述代码,预期输出显示:IsNullOrEmpty 对包含空格的字符串返回 false,而 IsNullOrWhiteSpace 对相同输入返回 true。这证实了空白字符在两种方法中的处理差异。
在早期C#版本中如何替代IsNullOrEmpty
在C# 6.0之前,没有 IsNullOrEmpty 方法,开发者通常使用逻辑或运算符组合两个条件: str == null || str.Length == 0 。这种写法功能等价,但略显冗长。从C# 7.0开始,还可以利用模式匹配简化为 str is null or "" ,提高了可读性。尽管现代C#推荐使用内置方法,但在维护旧项目或理解底层逻辑时,掌握这些替代方案仍有价值。

using System;
public class LegacyCheck
{
public static bool CheckString(string str)
{
// C# 6.0+ 推荐方式
if (string.IsNullOrEmpty(str))
return true;
// C# 5.0- 兼容方式
if (str == null || str.Length == 0)
return true;
// C# 7.0+ 模式匹配方式
if (str is null or "")
return true;
return false;
}
public static void Main()
{
Console.WriteLine(CheckString(null)); // True
Console.WriteLine(CheckString("")); // True
Console.WriteLine(CheckString("a")); // False
}
}
该程序验证了三种写法在 null、空串和非空串上的行为一致性。所有分支均正确返回预期布尔值,证明在无法使用 IsNullOrEmpty 时,这些替代方案能可靠工作。











