string.Equals 遇到空输入会返回什么
在 c# 中,string.equals 方法能够安全处理 null 字符串,不会抛出异常。当调用方或参数为 null 时,该方法会根据具体的重载签名和比较规则返回布尔值(通常为 false),从而允许代码在不进行显式判空的情况下继续执行逻辑。

using System;
class Program
{
static void Main()
{
string a = null;
string b = "test";
// 实例方法调用:a 为 null 时不抛异常
bool result1 = a.Equals(b);
Console.WriteLine(result1); // False
// 静态方法调用:推荐方式
bool result2 = string.Equals(a, b);
Console.WriteLine(result2); // False
// 静态方法指定比较类型
bool result3 = string.Equals(a, b, StringComparison.Ordinal);
Console.WriteLine(result3); // False
// 两个都为 null
bool result4 = string.Equals(null, null);
Console.WriteLine(result4); // True
}
}
上述代码展示了三种常见用法。使用实例方法 a.Equals(b) 时,如果 a 是 null,传统上会抛出 NullReferenceException,但在 .NET Framework 4.0+ 及 .NET Core/5+ 中,微软对字符串方法进行了优化,使其能安全处理 null 调用者。不过,最稳妥且语义最清晰的方式是使用静态方法 string.Equals(),它明确处理了双方可能为 null 的情况。当两个字符串均为 null 时,返回 true;当一个为 null 另一个不为空时,返回 false。
不同比较模式下的 null 行为差异
在使用 string.Equals的静态重载并指定 StringComparison 枚举时,null 的处理逻辑保持一致,但比较结果受文化敏感性和大小写规则影响。无论采用哪种比较模式,只要其中一个操作数为 null 而另一个不是,结果始终为 false。只有当两个操作数同时为 null 时,才返回 true。

using System;
class Program
{
static void Main()
{
string s1 = null;
string s2 = "ABC";
string s3 = "abc";
// Ordinal: 二进制比较
bool r1 = string.Equals(s1, s2, StringComparison.Ordinal);
Console.WriteLine(r1); // False
// CurrentCulture: 当前文化敏感
bool r2 = string.Equals(s1, s2, StringComparison.CurrentCulture);
Console.WriteLine(r2); // False
// InvariantCulture: 不变文化
bool r3 = string.Equals(s1, s2, StringComparison.InvariantCulture);
Console.WriteLine(r3); // False
// 两个 null 的比较
bool r4 = string.Equals(null, null, StringComparison.Ordinal);
Console.WriteLine(r4); // True
}
}
通过这段代码可以看出,StringComparison 的不同取值主要影响非 null 字符串之间的比较结果(如大小写折叠、重音处理等),但对于涉及 null 的比较,框架内部会优先检查空值状态。如果检测到任一参数为 null,则直接根据“是否两者皆空”的逻辑返回结果,不再进入复杂的字符比较流程。这种设计保证了性能和安全性的平衡。
基于程序中某个输入、条件或结果的具体问题
在实际开发中,经常需要判断用户输入是否为空字符串或仅包含空白字符。虽然 string.Equals 能处理 null,但它无法区分 null 和空字符串 ""。如果需要严格区分这两种状态,或者需要去除空白后判断,应结合其他方法使用。
using System;
class Program
{
static void Main()
{
string input1 = null;
string input2 = "";
string input3 = " ";
// Equals 无法区分 null 和 ""
Console.WriteLine(string.Equals(input1, "")); // False
Console.WriteLine(string.Equals(input2, "")); // True
// IsNullOrEmpty 同时检查 null 和 ""
Console.WriteLine(string.IsNullOrEmpty(input1)); // True
Console.WriteLine(string.IsNullOrEmpty(input2)); // True
// IsNullOrWhiteSpace 额外检查空白字符
Console.WriteLine(string.IsNullOrWhiteSpace(input3)); // True
}
}
从输出结果可见,string.Equals(input, "") 在 input 为 null 时返回 false,而在 input 为空字符串时返回 true。这意味着如果你用 Equals 来检查“是否为空”,必须小心处理 null 情况。推荐使用 string.IsNullOrEmpty() 或 string.IsNullOrWhiteSpace() 来处理这类业务逻辑,它们更直观地表达了意图,并且内部实现也经过了高度优化。











