值
规则 ID
CA1820
类别
“性能”
修复是中断修复还是非中断修复
非中断
原因
使用了 Object.Equals 将字符串与空字符串进行比较。
规则说明
使用 String.Length 属性或 String.IsNullOrEmpty 方法比较字符串比使用 Equals 更快。 这是因为 Equals 执行的 MSIL 指令比 IsNullOrEmpty 或执行以用于检索 Length 属性值并将其与零进行比较的指令数要多得多。
对于 NULL 字符串,Equals 和 <string>.Length == 0 的行为不同。 如果尝试获取 NULL 字符串的 Length 属性值,则公共语言运行时将引发 System.NullReferenceException。 如果在 NULL 字符串和空字符串之间执行比较,则公共语言运行时不会引发异常,并将返回 false。 测试 NULL 不会对这两种方法的相对性能产生显著影响。 面向 .NET Framework 2.0 或更高版本时,请使用 IsNullOrEmpty 方法。 否则,请尽可能使用 Length == 0 比较。
如何解决冲突
若要解决此规则的冲突,请更改比较以使用 IsNullOrEmpty 方法。
何时禁止显示警告
如果性能不是问题,可禁止显示此规则的警告。
示例
下面的示例演示了用于查找空字符串的不同技术。
public class StringTester
{
string s1 = "test";
public void EqualsTest()
{
// Violates rule: TestForEmptyStringsUsingStringLength.
if (s1 == "")
{
Console.WriteLine("s1 equals empty string.");
}
}
// Use for .NET Framework 1.0 and 1.1.
public void LengthTest()
{
// Satisfies rule: TestForEmptyStringsUsingStringLength.
if (s1 != null && s1.Length == 0)
{
Console.WriteLine("s1.Length == 0.");
}
}
// Use for .NET Framework 2.0.
public void NullOrEmptyTest()
{
// Satisfies rule: TestForEmptyStringsUsingStringLength.
if (!String.IsNullOrEmpty(s1))
{
Console.WriteLine("s1 != null and s1.Length != 0.");
}
}
}
本文系外文翻译,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文系外文翻译,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。