偶尔我喜欢花一些时间查看.NET代码,看看事情是如何在幕后实现的.我在String.Equals通过Reflector 查看方法时偶然发现了这个宝石.
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);
}
Run Code Online (Sandbox Code Playgroud)
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: …Run Code Online (Sandbox Code Playgroud) delegate void DelegateTest();
DelegateTest delTest;
Run Code Online (Sandbox Code Playgroud)
电话delTest.Invoke()和delTest()?之间的区别是什么?两者都会在当前线程上执行委托,对吧?
可能重复:
为什么检查这个!= null?
// Determines whether two strings match.
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public override bool Equals(Object obj)
{
//this is necessary to guard against reverse-pinvokes and
//other callers who do not use the callvirt instruction
if (this == null)
throw new NullReferenceException();
String str = obj as String;
if (str == null)
return false;
if (Object.ReferenceEquals(this, obj))
return true;
return EqualsHelper(this, str);
}
Run Code Online (Sandbox Code Playgroud)
我不理解的部分是它正在检查当前实例,this而不是null.评论有点令人困惑,所以我想知道这个评论究竟意味着什么?
任何人都可以给出一个例子,说明如果那个检查不存在,这可能会破坏,这是否意味着我还应该将检查放在我的课程中?
请考虑以下我正在审核的代码:
public override bool Equals(object other)
{
return !object.ReferenceEquals(null, this)
&& (object.ReferenceEquals(this, other)
|| ((other is MyType) && this.InternalEquals((MyType)other)));
}
Run Code Online (Sandbox Code Playgroud)
这段代码的第一行引发了我的好奇心.每当this为null时,该方法应返回false.现在我很确定程序员打算用!object.ReferenceEquals(other, null)快捷方式编写null,但是他坚持认为this可以为null.我坚持认为它不能(除非有人使用直接内存操作).我们应该留下吗?