我有这个代码:
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.MinValue
到Int64.MaxValue
.显然,当转换为Int32
时,这可能会引发溢出,因为范围更长。 - 在 32 位操作系统上,IntPtr 可以从
Int32.MinValue
到Int32.MaxValue
,因此您可以将其转换为Int64
并Int32
,因为该值将始终在该范围内。