:'无法将类型为'System .__ ComObject'的COM对象转换为接口类型 [英] : 'Unable to cast COM object of type 'System.__ComObject' to interface type

查看:319
本文介绍了:'无法将类型为'System .__ ComObject'的COM对象转换为接口类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到以下错误:

System.InvalidCastException:'无法将类型'System .__ ComObject'的COM对象转换为接口类型'Microsoft.Office.Interop.Outlook.MailItem'.此操作失败是因为由于以下错误,IID为'{00063034-0000-0000-C000-000000000046}'的COM组件上的COM组件上的QueryInterface调用由于以下错误而失败:不支持此类接口(HRESULT的异常:0x80004002(E_NOINTERFACE)) .'

System.InvalidCastException: 'Unable to cast COM object of type 'System.__ComObject' to interface type 'Microsoft.Office.Interop.Outlook.MailItem'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{00063034-0000-0000-C000-000000000046}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).'

产生错误的代码:

foreach (MailItem item in mailItems)
{
}

推荐答案

mailItems可能包含除循环中定义的Microsoft.Office.Interop.Outlook.MailItem以外的更多对象.最安全的方法是使用object类型迭代mailItems,然后在运行Outlook处理程序之前使用as运算符检查其类型:

It is possible that mailItems contains more objects other than Microsoft.Office.Interop.Outlook.MailItem as defined in the loop. The safest way is using object type to iterate mailItems, then check its type with as operator before running Outlook handler:

foreach (object item in mailItems)
{
    // try casting to Outlook.MailItem first
    var obj = item as Outlook.MailItem;

    // check if the conversion works and UnRead property can be accessed as well
    if (obj != null && obj.UnRead == true)
    {
        // do something
    }
    else
    {
        // do something else
    }
}

这篇关于:'无法将类型为'System .__ ComObject'的COM对象转换为接口类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆