【发布时间】:2018-03-02 12:05:34
【问题描述】:
我有这个代码:
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 位机器上抛出异常还是不会?
【问题讨论】:
-
是
-1你看到的东西吗? 将static readonly IntPtr MinusOne = new IntPtr(-1);- 然后与MinusOne比较 - 工作?您可能需要:static readonly IntPtr MinusOne = IntPtr.Size == 4 ? new IntPtr(-1) : new IntPtr(-1L); -
@MarcGravell omg,这也是一个好点,我会试试的。