C# IntPtr.ToInt32()会在64位机器上抛出EXCTION,但IntPtrToInt64()会在32位机器上抛出EXCTION吗?
我有以下代码:C# IntPtr.ToInt32()会在64位机器上抛出EXCTION,但IntPtrToInt64()会在32位机器上抛出EXCTION吗?,c#,intptr,C#,Intptr,我有以下代码: if (hnd == IntPtr.Zero || hnd.ToInt32() == -1) hnd是一个IntPtr 这会抛出溢出异常,所以我将其修改为 if (hnd == IntPtr.Zero || hnd.ToInt64() == -1) 文档中说ToInt32可以抛出异常,但ToInt64不能(?) 所以问题是: hnd.ToInt64()会在32位计算机上引发异常还是不会引发异常?以下状态: 这种类型的实例在32位硬件和操作系统上预期为32位,在64位硬件和操
if (hnd == IntPtr.Zero || hnd.ToInt32() == -1)
hnd
是一个IntPtr
这会抛出溢出异常,所以我将其修改为
if (hnd == IntPtr.Zero || hnd.ToInt64() == -1)
文档中说ToInt32可以抛出异常,但ToInt64不能(?)
所以问题是:
hnd.ToInt64()会在32位计算机上引发异常还是不会引发异常?以下状态:
这种类型的实例在32位硬件和操作系统上预期为32位,在64位硬件和操作系统上预期为64位
因此:
- 在64位操作系统上,IntPtr可以从
到Int64.MinValue
。显然,当转换为Int64.MaxValue
时会引发溢出,因为范围更长Int32
- 在32位操作系统上,IntPtr可以从
到Int32.MinValue
,因此您可以将其转换为Int32.MaxValue
和Int64
,因为值始终在范围内Int32
-1
是你看到的东西吗?将static readonly IntPtr MinusOne=new IntPtr(-1)代码>-然后与最小值
-进行比较-是否有效?您可能需要:static readonly IntPtr MinusOne=IntPtr.Size==4?新IntPtr(-1):新IntPtr(-1L)代码>@MarcGravel天哪,这也是一个很好的观点,我会试试看。
//
// 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();