检查HRESULT为S_OK的方法的返回值

时间:2012-10-30 18:39:15

标签: c# hresult

如何将方法返回的值与HRESULT进行比较?我尝试了这个,但它不起作用:

FPropStg.DeleteMultiple(1, psProp) == VSConstants.S_OK

DeleteMultiple()的类型定义是:

HRESULT IPropertyStorage.DeleteMultiple(Ulong, Propspec)

我写过VSConstants.S_OK。有没有办法直接写S_OK?我试图这样做,但得到的错误表明当前上下文中不存在S_OK

我还针对Windows common system-wide codes检查了HRESULT。但我收到的HRESULT的价值不在该列表中。请注意,我已添加了名称空间System.ExceptionSystem.Security.Cryptography.StrongNameSignatureInformation

所有这一切,我基本上有两个问题:

  1. 有没有办法写S_OK代替VSConstants.S_OK
  2. 如何将方法的返回值与S_OK
  3. 进行比较
    HRESULT hr = FPropStg.DeleteMultiple(1, psProp);
    
    if (hr == S_OK) // S_OK does not exist in the current context...
    {
    }
    

3 个答案:

答案 0 :(得分:5)

如果您将 PreserveSig 设置为 false ,该怎么办?像这样:

你声明了与此类似的功能(我做了,我不知道确切的签名......但是你这样做了)

[DllImport("ole32.dll", EntryPoint = "DeleteMultiple", ExactSpelling = true, PreserveSig = false)]
public static extern void DeleteMultiple(ulong cpspec, PropSpec[] rgpspec);

并以这种方式称呼

try
{
    FPropStg.DeleteMultiple(1, psProp);
}
catch (Exception exp)
{
    MessageBox.Show(exp.Message, "Error on DeleteMutiple");
}

说明 PreserveSig false 时,您可以省略返回的 HRESULT 值,但内部此值为实际上已经检查过了,所以如果 HRESULT S_OK 不同,则会抛出异常。

答案 1 :(得分:4)

您可以使用此枚举来定义确定,它来自pinvoke

enum HRESULT : long
{
S_FALSE = 0x0001,
S_OK = 0x0000,
E_INVALIDARG = 0x80070057,
E_OUTOFMEMORY = 0x8007000E
}

答案 2 :(得分:3)

HRESULT is simply an unsigned 32bit integer value。您可以构建自己的常量类来帮助您进行这些比较:

public static class HResults
{
    public static readonly int S_OK = 0;
    public static readonly int STG_E_ACCESSDENIED =  unchecked((int)0x80030005);
}

用过:

if (HResults.S_OK == FPropStg.DeleteMultiple(1, psProp))
{
    // ...
}