![](/img/trans.png)
[英]Unable to cast COM object of type 'System.__ComObject' with STAThread attribute
[英]: 'Unable to cast COM object of type 'System.__ComObject' to interface type
我收到以下错误:
System.InvalidCastException:'无法将类型'System .__ ComObject'的COM对象转换为接口类型'Microsoft.Office.Interop.Outlook.MailItem'。 此操作失败,因为具有以下错误的IID为“ {00063034-0000-0000-C000-000000000046}”的COM组件上的COM接口上的QueryInterface调用由于以下错误而失败:不支持此类接口(HRESULT的异常:0x80004002(E_NOINTERFACE)) 。”
产生错误的代码:
foreach (MailItem item in mailItems)
{
}
mailItems
可能包含除循环中定义的Microsoft.Office.Interop.Outlook.MailItem
以外的更多对象。 最安全的方法是使用object
类型来迭代mailItems
,然后在运行Outlook处理程序之前使用as
运算符检查其类型:
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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.