不够。在c#中,`is not null` 仅能判断对象引用是否为空,无法区分空字符串("")和空白字符串(" ")。要确保字符串既不为null也不为空或纯空格,应使用 string.isnullorempty() 或 string.isnullorwhitespace()。

如何判断字符串非空且非空白
直接回答:使用 string.IsNullOrWhiteSpace() 是最稳妥的做法。它内部结合了null检查、空字符串检查和空白字符检查,返回false即表示字符串包含有效内容。

using System;
public class Program
{
public static void Main()
{
string input = " ";
// 错误做法:仅判断非null
if (input is not null)
{
Console.WriteLine("Is Not Null: True");
}
else
{
Console.WriteLine("Is Not Null: False");
}
// 正确做法:判断非空且非空白
if (!string.IsNullOrWhiteSpace(input))
{
Console.WriteLine("Is Valid: True");
}
else
{
Console.WriteLine("Is Valid: False");
}
}
}
运行结果:
Is Not Null: True
Is Valid: False
不同输入下的行为对比
直接回答:string.IsNullOrEmpty() 与 string.IsNullOrWhiteSpace() 的主要区别在于对空白字符的处理。前者只检查null和"",后者额外检查由空白字符组成的字符串。

using System;
public class Program
{
public static void Main()
{
string[] inputs = { null, "", " ", "a" };
foreach (var s in inputs)
{
bool isEmpty = string.IsNullOrEmpty(s);
bool isNullOrWhiteSpace = string.IsNullOrWhiteSpace(s);
Console.WriteLine($"Input: {s == null ? "null" : $"\"{s}\""} | IsNullOrEmpty: {isEmpty} | IsNullOrWhiteSpace: {isNullOrWhiteSpace}");
}
}
}
运行结果:
Input: null | IsNullOrEmpty: True | IsNullOrWhiteSpace: True
Input: "" | IsNullOrEmpty: True | IsNullOrWhiteSpace: True
Input: " " | IsNullOrEmpty: False | IsNullOrWhiteSpace: True
Input: "a" | IsNullOrEmpty: False | IsNullOrWhiteSpace: False
当输入为null时is not null的行为
直接回答:当输入为null时,is not null 表达式返回false,而 string.IsNullOrWhiteSpace(null) 返回true。这意味着两者在null处理上逻辑相反,不能混用。











