当我尝试从com异常中获取HRESULT的值时,我收到警告,并且我怀疑这是否是在C#中处理COM异常的正确方法,请告知代码如下所示。
try
{
...
}
catch (System.Runtime.InteropServices.COMException comex)
{
// Warning 8 Comparison to integral constant is useless; the constant is outside the range of type 'int'
if (comex.ErrorCode == Constants.E_FAIL)
{
}
}
E_FAIL定义为
public const UInt32 E_FAIL = 0x80004005;
答案 0 :(得分:2)
可以说,将Exception.HResult
定义为UInt32
而不是Int32
又名int
,与Win32 API更加一致。
可能没有这样做,因为UInt32不符合CLS。
我建议你将常量定义为int:
public const int E_FAIL = unchecked((int)0x80004005);
答案 1 :(得分:0)
comex.ErrorCode
是Int32(请参阅here),您的Constants.E_FAIL
超出了Int32限制(Int32.MaxValue
= 7FFFFFFF)。
我看到你正在将Int32与UInt32进行比较:你应该在比较之前转换后者...
例如,您可以使用
if (comex.ErrorCode == unchecked((int)Constants.E_FAIL))
答案 2 :(得分:0)
你可以这样做:
if (comex.ErrorCode == unchecked((int)Constants.E_FAIL))
{
// do stuff
}
但请注意,您可能永远不会看到一些错误代码,因为它们已映射到specific exceptions,但它看起来不像E_FAIL
。