IntPtr.ToInt32() 在 64 位上抛出 excption,但 IntPtrToInt64() 会在 32



我有这个代码:

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

hnd是一个IntPtr

这抛出了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 位机器上抛出异常还是不会?

文档指出:

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

所以:

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

相关内容

最新更新