【发布时间】:2011-03-09 18:44:08
【问题描述】:
有时我喜欢花一些时间查看 .NET 代码,只是为了看看幕后是如何实现的。我在通过 Reflector 查看 String.Equals 方法时偶然发现了这个宝石。
C#
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public override bool Equals(object obj)
{
string strB = obj as string;
if ((strB == null) && (this != null))
{
return false;
}
return EqualsHelper(this, strB);
}
IL
.method public hidebysig virtual instance bool Equals(object obj) cil managed
{
.custom instance void System.Runtime.ConstrainedExecution.ReliabilityContractAttribute::.ctor(valuetype System.Runtime.ConstrainedExecution.Consistency, valuetype System.Runtime.ConstrainedExecution.Cer) = { int32(3) int32(1) }
.maxstack 2
.locals init (
[0] string str)
L_0000: ldarg.1
L_0001: isinst string
L_0006: stloc.0
L_0007: ldloc.0
L_0008: brtrue.s L_000f
L_000a: ldarg.0
L_000b: brfalse.s L_000f
L_000d: ldc.i4.0
L_000e: ret
L_000f: ldarg.0
L_0010: ldloc.0
L_0011: call bool System.String::EqualsHelper(string, string)
L_0016: ret
}
检查this 和null 的原因是什么?我必须假设这是有目的的,否则现在可能已经被捕获并删除了。
【问题讨论】:
-
你也可以看看 EqualsHelper 吗?他们似乎想使用 EqualsHelper,但它可能无法按照他们想要的方式处理空值。
-
这特别有趣,因为文档明确指出,如果实例为空,Equals 将抛出 NullReferenceException ......
-
我猜这要么是疏忽,要么与
EqualsHelper的工作方式有关。我根本看不出需要if语句,假设strB是null而this不是时EqualsHelper将返回false。但也许我不够聪明,无法理解:) -
@womp - 在 4.0 中,第一行是
if(this == null) throw new NullReferenceException(),所以在这个意义上是正确的。 -
这段代码是在 1999 年 12 月 13 日之前编写的,那一天 C# 团队致力于如何实现空值检查。 blogs.msdn.com/b/ericgu/archive/2008/07/02/…