2012-10-20 35 views
3

我只是發現它在dotPeek,String.cs:爲什麼在overriden Object.Equals方法中拋出NullReferenceException?

[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] 
[__DynamicallyInvokable] 
public override bool Equals(object obj) 
{ 
    if (this == null) 
    throw new NullReferenceException(); 
    string strB = obj as string; 
    if (strB == null) 
    return false; 
    if (object.ReferenceEquals((object) this, obj)) 
    return true; 
    if (this.Length != strB.Length) 
    return false; 
    else 
    return string.EqualsHelper(this, strB); 
} 

在第二線引發NullReferenceException如果== NULL。那麼如何調用空對象的方法呢?

MSDN說: 請注意,應用程序拋出ArgumentNullException異常,而不是此處討論的NullReferenceException異常。

下面的Microsoft中間語言(MSIL)指令拋出的NullReferenceException:

callvirt 
cpblk 
cpobj 
initblk 
ldelem.<type> 
ldelema 
ldfld 
ldflda 
ldind.<type> 
ldlen 
stelem.<type> 
stfld 
stind.<type> 
throw 
unbox 

如果我得到它,異常之前拋出進入方法體。對?那麼需要從方法拋出NullReferenceException呢? __DynamicallyInvokableAttribute強制方法被稱爲繞過任何檢查?或者是其他東西?

謝謝。

+0

檢查此問題:http://stackoverflow.com/questions/10625326/this-null-inside-net-instance-method-why-is-that-possible – empi

+0

重複的http://stackoverflow.com/questions/3143498 /爲什麼 - 檢查 - 這個空 –

回答

4

在輸入空對象之前,C#會使用callvirt,您將在其中得到NullReferenceException。但是由於BCL是爲大量的語言製作的,所以他們在使用調用指令的某些中心部分(例如字符串)中防範了空對象。

託管C++是呼叫指令中最顯着的用戶。

這樣做是爲了幫助調試一點(據我所知),但它在整個BCL中並不一致。

相關問題