【问题标题】:IntPtr.ToInt32() throws excption on 64bit, but will IntPtrToInt64() throw on 32bit machine?IntPtr.ToInt32() 在 64 位上会抛出异常,但 IntPtr ToInt64() 会在 32 位机器上抛出异常吗?
【发布时间】:2018-03-02 12:05:34
【问题描述】:

我有这个代码:

if (hnd == IntPtr.Zero || hnd.ToInt32() == -1)

hndIntPtr

这会抛出OverflowException,所以我修改为

 if (hnd == IntPtr.Zero || hnd.ToInt64() == -1)

文档说 ToInt32 可以抛出异常,但 ToInt64 不能(?)。

  //
// Summary:
//     Converts the value of this instance to a 32-bit signed integer.
//
// Returns:
//     A 32-bit signed integer equal to the value of this instance.
//
// Exceptions:
//   T:System.OverflowException:
//     On a 64-bit platform, the value of this instance is too large or too small to
//     represent as a 32-bit signed integer.
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[SecuritySafeCritical]
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
public int ToInt32();
//
// Summary:
//     Converts the value of this instance to a 64-bit signed integer.
//
// Returns:
//     A 64-bit signed integer equal to the value of this instance.
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[SecuritySafeCritical]
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
public long ToInt64();

所以问题: hnd.ToInt64() 会在 32 位机器上抛出异常还是不会?

【问题讨论】:

  • -1 你看到的东西吗?static readonly IntPtr MinusOne = new IntPtr(-1); - 然后与MinusOne 比较 - 工作?您可能需要:static readonly IntPtr MinusOne = IntPtr.Size == 4 ? new IntPtr(-1) : new IntPtr(-1L);
  • @MarcGravell omg,这也是一个好点,我会试试的。

标签: c# intptr


【解决方案1】:

documentation 声明:

这种类型的实例预计在 32 位硬件和操作系统上为 32 位,在 64 位硬件和操作系统上为 64 位

所以:

  • 在 64 位操作系统上,IntPtr 可以从 Int64.MinValue 变为 Int64.MaxValue。显然,当转换为 Int32 时,这可能会引发溢出,因为范围更长。
  • 在 32 位操作系统上,IntPtr 可以从 Int32.MinValue 变为 Int32.MaxValue,因此您可以将其转换为 Int64Int32,因为该值始终在范围内。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-25
    • 2012-06-26
    • 2011-11-02
    • 1970-01-01
    • 2019-09-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多