string判空用is null模式的基本用法是什么
在c#中判断字符串是否为null,直接使用if (str is null)即可。这种写法利用了c# 7.0引入的模式匹配特性,语义清晰且能避免调用tostring()可能引发的异常。与传统的== null相比,它在逻辑上完全等价,但更符合现代c#的编程风格。

using System;
class Program
{
static void Main()
{
string str = null;
// 使用 is null 模式进行判断
if (str is null)
{
Console.WriteLine("字符串为 null");
}
else
{
Console.WriteLine("字符串不为 null");
}
}
}运行上述代码将输出“字符串为 null”。这里的关键在于is null直接检查引用是否为空,不会触发任何虚方法调用或装箱操作,因此是安全且高效的。
is null与== null及String.IsNullOrEmpty的区别是什么
is null仅检查引用是否为null,不检查字符串内容是否为空(即长度为0)。而String.IsNullOrEmpty(str)会同时检查null和空字符串。传统== null在行为上与is null一致,但is null提供了更明确的模式匹配意图。

using System;
class Program
{
static void Main()
{
string s1 = null;
string s2 = "";
string s3 = "hello";
CheckNull(s1);
CheckNull(s2);
CheckNull(s3);
}
static void CheckNull(string str)
{
if (str is null)
{
Console.WriteLine($"{str ?? "(null)"} is null");
}
else if (str == "")
{
Console.WriteLine($"'{str}' is empty");
}
else
{
Console.WriteLine($"'{str}' has content");
}
}
}该程序展示了三种不同输入下的分支结果:对于null,进入第一个分支;对于空字符串,进入第二个分支;对于有内容的字符串,进入第三个分支。这说明了is null并不涵盖空字符串的情况,开发者需根据需求组合判断。
当字符串变量为null时,is null模式是否会抛出异常
不会。is null模式在遇到null值时只会返回true或false,绝不会抛出异常。这是它比某些其他判空方式更安全的原因之一,特别是在处理可能为null的对象引用时。

using System;
class Program
{
static void Main()
{
string str = null;
try
{
// 使用 is null 模式,不会抛出异常
bool result = str is null;
Console.WriteLine($"Result: {result}");
}
catch (Exception ex)
{
Console.WriteLine($"Exception: {ex.Message}");
}
}
}运行此代码将输出“Result: True”,证明is null在处理null引用时是安全的。相比之下,如果尝试访问str.Length则会抛出NullReferenceException。因此,在使用is null进行前置检查后,后续对字符串的操作才是安全的。


















