为什么IntPtr.ToInt32在64位模式下抛出OverflowException并且Explicit(IntPtr到Int32)不

axk*_*axk 5 clr 64-bit intptr

运营商在MSDN上的描述有一个注释:

仅当值的值需要比当前平台支持的更多位时才抛出异常.

虽然ToInt32我的描述不是这样,但我认为标题不完全正确(为了简洁起见),

更正确的问题是:"为什么IntPtr.ToInt32会引发OverflowException在64位模式,价值观适应的Int32和显式(IntPtr的到Int32)已不"

反编译IntPtr ToInt32和运算符看起来非常相似:

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;
}
Run Code Online (Sandbox Code Playgroud)

我想知道是什么让ToInt32抛出异常,是不安全的关键字?

Han*_*ant 11

你的反汇编程序无法在这里做正确的工作,mscorlib.dll很特别.它不是AnyCPU程序集,Microsoft根据处理器体系结构构建并提供不同版本的程序集.我建议你使用参考源,你将获得原始的源代码.看起来像这样:

    [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
    }
Run Code Online (Sandbox Code Playgroud)

它是提供OverflowException 的checked关键字.