2009-09-17 83 views
6

我有打算返回所有電子郵件主題行的文件夾下面的類枚舉Outlook郵箱使用Visual Studio

這是Visual Studio 2008中對Outlook 2007中的Windows 7 64位

using System; 
using System.Windows; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using Microsoft.Office.Interop.Outlook; 

namespace MarketingEmails 
{ 
public class MailUtils 
{ 

    public static string[] processMailMessages(object outlookFolder) 
    // Given an Outlook folder as an object reference, return 
    // a list of all the email subjects in that folder 
    { 

     // Set a local object from the folder passed in 
     Folder theMailFolder = (Folder)outlookFolder; 

     string[] listSubjects = new string[theMailFolder.Items.Count]; 
     int itemCount = 0; 

     // Now process the MAIL items 
     foreach (MailItem oItem in theMailFolder.Items) 
     { 
      listSubjects[itemCount] = oItem.Subject.ToString(); 
      itemCount++; 
     } 
     return listSubjects; 
    } 

} 
運行

}

然而代碼拋出下面的異常:

無法轉換COM對象類型的「系統.__ ComObject」在terface類型'Microsoft.Office.Interop.Outlook.MailItem'。此操作失敗的原因是對IID「{00063034-0000-0000-C000-000000000046}」的界面處的COM組件調用QueryInterface失敗,因爲以下錯誤:不支持此接口(從HRESULT異常:0x80004002(E_NOINTERFACE)) 。

我的理解是,因爲它試圖處理在選擇郵箱ReportItem已發生的錯誤。

我不明白的是爲什麼它試圖當我指定RO工藝非郵件項目:

foreach (MailItem oItem in theMailFolder.Items) 

如果我想它來處理郵箱舉報物品條目我會採寫:

foreach (ReportItem oItem in theMailFolder.Items) 

我倒是十分喜歡的瞭解一下,如果這是一個錯誤,或者如果它只是我的錯誤理解

問候, 奈傑爾Ainscoe

回答

8

的原因在於藏品既包含的MailItem和ReportItem實例。在左側指定MailItem不會過濾列表,它只是說明您希望列表中的類型。

你需要做什麼是你想要像這樣

foreach (MailItem oItem in theMailFolder.Items.OfType<MailItem>()) { 
    .. 
} 

的OfType方法將只匹配特定類型的集合中返回值的類型的過濾器。

+0

這是一種享受 - 謝謝 – 2009-09-18 09:20:33

+0

哦,不錯的把戲JaredPar很酷。 – 2010-12-29 22:40:07

2

foreach循環不按照類型過濾的類型聲明 - 它拋出一個異常,而不是,因爲你已經注意到了。

它這樣做是因爲foreach年推出的C#1.0,​​沒有泛型supprot。因此,編譯器無法知道IEnumerator返回的是哪種類型。 (如果收集不執行IEnumerable<T>,則仍然如此)。 Nitpickers:我知道即使在C#1中編寫強類型枚舉器也是可能的(例如List<T>)。絕大多數不是。

那麼,如果你不小心把錯誤的類型放在foreach,你寧願讓它拋出一個異常,而不是神祕地不做任何事情。

正如JaredPar解釋,你應該使用OfType方法。

+1

好吧,這引發了一些對我來說無稽之談。感謝您的照明。 – 2009-09-18 10:08:47