不一样。字符串为 null 表示该变量未指向任何内存对象,而空串 "" 是一个长度为 0 的有效对象实例。在 c# 中判断两者需使用不同的条件:检查是否为 null 必须显式比较或使用 is null,而判断空串通常结合长度属性或专用方法。若直接对 null 调用实例方法(如 .length)会抛出异常,因此安全的判空逻辑需先处理 null 情况。

string.IsNullOrEmpty() 如何同时处理 null 和空串?
该方法用于一次性判断字符串是否为 null 或空串 ""。它内部先检查引用是否为 null,若是则返回 true;否则检查 Length 属性是否等于 0。这种写法避免了分别编写两个条件的冗余代码,是处理用户输入或配置项时最常用的标准做法。

using System;
public class Program
{
public static void Main()
{
string nullStr = null;
string emptyStr = "";
string normalStr = "Hello";
Console.WriteLine(IsNullOrEmpty(nullStr)); // True
Console.WriteLine(IsNullOrEmpty(emptyStr)); // True
Console.WriteLine(IsNullOrEmpty(normalStr)); // False
}
public static bool IsNullOrEmpty(string str)
{
return string.IsNullOrEmpty(str);
}
}
string.IsNullOrWhiteSpace() 与空串判别的区别是什么?
该方法不仅检查 null 和空串 "",还会将仅包含空白字符(如空格、制表符、换行符)的字符串视为“空”。对于需要严格区分“空内容”和“纯空白内容”的场景,应使用此方法或手动检查 Trim().Length == 0。例如,用户输入单个空格时,IsNullOrEmpty 返回 false,而 IsNullOrWhiteSpace 返回 true。

using System;
public class Program
{
public static void Main()
{
string spaceStr = " ";
string emptyStr = "";
string nullStr = null;
Console.WriteLine(NullOrWhiteSpace(spaceStr)); // True
Console.WriteLine(NullOrWhiteSpace(emptyStr)); // True
Console.WriteLine(NullOrWhiteSpace(nullStr)); // True
}
}
为什么不能直接用 str.Length == 0 判断所有空值?
因为 Length 是 string 类型的实例属性,当变量为 null 时访问该属性会触发 NullReferenceException。只有确保字符串非 null 后,才能安全使用 Length 判断是否为空串。在实际开发中,若只需判断空串且已知变量不为 null,可直接使用 str.Length == 0 或 str == "",但混合场景下必须优先处理 null。


















