【问题标题】:Why IntPtr.ToInt32 throws OverflowException in 64 bit mode and Explicit(IntPtr to Int32) doesn't为什么 IntPtr.ToInt32 在 64 位模式下抛出 OverflowException 而 Explicit(IntPtr to Int32) 不会
【发布时间】:2012-06-26 21:31:15
【问题描述】:

运营商description on MSDN有备注:

只有当 value 的值需要更多位时才会抛出异常 超出当前平台支持的范围。

虽然ToInt32's description 没有,所以我想标题并不完全正确(为简洁起见),

一个更正确的问题是:“为什么IntPtr.ToInt32 在 64 位模式下抛出 OverflowException 以获取 适合 Int32 而 Explicit(IntPtr to 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抛出异常,是unsafe关键字吗?

【问题讨论】:

    标签: 64-bit clr intptr


    【解决方案1】:

    你的反汇编程序在这里不能正常工作,mscorlib.dll 是特殊的。它不是 AnyCPU 组件,微软基于处理器架构构建并发布了不同版本的它。我建议您使用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
        }
    

    checked 关键字提供了溢出异常。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-28
      • 2019-11-28
      • 2013-02-18
      • 2014-12-23
      相关资源
      最近更新 更多