![](/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.