在c#中判断字符串为空时抛出空引用异常,是因为变量本身是null,而调用实例方法或访问属性会触发对null对象的成员查找。安全判空的写法是使用静态方法 string.isnullorempty() 或 string.isnullorwhitespace(),或者使用模式匹配语法 str is null。

string.IsNullOrEmpty() 与 == "" 的区别是什么
使用 string.IsNullOrEmpty() 可以安全地检查字符串是否为null或空字符串,而直接使用 == "" 在字符串为null时会抛出异常。前者是推荐的安全做法。

using System;
class Program
{
static void Main()
{
string nullStr = null;
string emptyStr = "";
// 安全判空
if (string.IsNullOrEmpty(nullStr))
{
Console.WriteLine("nullStr is null or empty");
}
if (string.IsNullOrEmpty(emptyStr))
{
Console.WriteLine("emptyStr is null or empty");
}
// 不安全判空(会抛异常)
try
{
if (nullStr == "")
{
Console.WriteLine("This will not print");
}
}
catch (NullReferenceException ex)
{
Console.WriteLine($"Exception: {ex.Message}");
}
}
}
string.IsNullOrWhiteSpace() 处理空白字符的效果如何
string.IsNullOrWhiteSpace() 不仅检查null和空字符串,还会检查只包含空白字符(如空格、制表符、换行符)的字符串。这对于用户输入验证非常有用。

using System;
class Program
{
static void Main()
{
string spaceStr = " ";
if (string.IsNullOrWhiteSpace(spaceStr))
{
Console.WriteLine("spaceStr is null, empty, or whitespace");
}
if (string.IsNullOrEmpty(spaceStr))
{
Console.WriteLine("spaceStr is null or empty");
}
else
{
Console.WriteLine("spaceStr is not null or empty");
}
}
}
当字符串为null时,Length 属性会引发什么异常
当字符串为null时,访问 Length 属性会直接抛出 NullReferenceException,因为无法在null对象上访问任何实例成员。这是最典型的空引用异常场景之一。











