: 'Unable to cast COM object of type 'System.__ComObject' to interface type

别来无恙 提交于 2019-12-24 20:05:36

问题


I am getting the following error:

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)).'

The code from which the error arises:

foreach (MailItem item in mailItems)
{
}

回答1:


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
    }
}


来源:https://stackoverflow.com/questions/48204385/unable-to-cast-com-object-of-type-system-comobject-to-interface-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!