2012-06-25 18 views
4

經營者的description on MSDN有一句話:爲什麼IntPtr.ToInt32拋出OverflowException異常在64位模式和顯式(IntPtr的到Int32)已不

一個例外是隻有拋出如果value的值需要更多的位 比目前的平臺支持。

ToInt32's description沒有,所以我想的標題是不是(爲簡便起見)完全正確,

更正確的問題是:「爲什麼IntPtr.ToInt32拋出OverflowException在64位模式的值是配合在的Int32和顯式(IntPtr的到Int32)已不」

在反編譯IntPtrToInt32和運營商看起來非常相似:

public static explicit operator int(IntPtr value) 
{ 
    return (int) value.m_value; 
} 

[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] 
public unsafe int ToInt32() 
{ 
    return (int) this.m_value; 
} 

我想知道是什麼讓ToInt32拋出異常,是不安全的關鍵字?

回答

8

你的反彙編程序不能在這裏做適當的工作,mscorlib.dll是特殊的。它不是一個AnyCPU程序集,Microsoft根據處理器體系結構構建併發布了它的不同版本。我建議你使用Reference Source,你會得到原始的源代碼。它看起來像這樣:

[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] 
    public unsafe int ToInt32() { 
     #if WIN32 
      return (int)m_value; 
     #else 
      long l = (long)m_value; 
      return checked((int)l); 
     #endif 
    } 

這是檢查關鍵字,提供了OverflowException異常。

相關問題