可以,c# 属性模式(property pattern)结合常量模式或子模式可以直接判断字符串长度为 0。最简洁的做法是使用 "" 常量模式进行精确匹配,或者使用 length == 0 的子模式表达式。当输入字符串为空时,匹配成功;否则匹配失败。

"" 常量模式如何匹配空字符串
使用双引号包裹的 "" 作为常量模式,专门用于匹配值为空的字符串。这是处理空字符串最直接的方式,无需访问 Length 属性。

using System;
public class Program
{
public static void Main()
{
string input = "";
if (input is "")
{
Console.WriteLine("String is empty");
}
else
{
Console.WriteLine("String is not empty");
}
}
}
运行结果:
String is empty
Length == 0 子模式如何判断长度
通过 Length == 0 子模式,可以显式检查字符串的 Length 属性是否为零。这种方式在需要同时检查其他属性或更复杂逻辑时非常有用。

using System;
public class Program
{
public static void Main()
{
string input = "";
if (input is { Length: 0 })
{
Console.WriteLine("String length is zero");
}
else
{
Console.WriteLine("String length is not zero");
}
}
}
运行结果:
String length is zero
基于程序中某个输入、条件或结果的具体问题
当输入为 null 时,上述两种模式都会抛出 NullReferenceException。这是因为属性模式在解构对象时会尝试访问其成员,而 null 没有成员。因此,在使用属性模式判断字符串长度前,必须确保字符串不为 null,或使用 is not null 进行前置检查。











