我有下面的类,用于返回文件夹中所有电子邮件的主题行
它是Visual 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;
}
}}
但是,代码在下面抛出异常:
无法将类型为“System.__ComObject”的COM对象转换为接口类型'Microsoft.Office.Interop.Outlook.MailItem‘。此操作失败,因为对IID‘{00063034-0000-0000-C000-000000000046}的接口的COM组件的QueryInterface调用失败,原因是以下错误:不支持此类接口( HRESULT: 0x80004002 (E_NOINTERFACE)例外)。
据我了解,发生错误的原因是它试图在选定邮箱中处理ReportItem。
我不明白的是,当我指定了时,为什么要尝试处理非邮件项:
foreach (MailItem oItem in theMailFolder.Items)如果我想让它处理邮箱中的报表项,我会写:
foreach (ReportItem oItem in theMailFolder.Items) 我很想弄清楚这是个错误还是我的误解。
你好,Nigel Ainscoe
发布于 2009-09-17 15:32:09
正如您已经注意到的,foreach循环中的类型声明不按类型进行筛选,而是抛出异常。
这是因为foreach是在C# 1.0中引入的,它不支持泛型。因此,编译器无法知道IEnumerator返回的类型。(如果集合不实现IEnumerable<T>,则仍然是这样)。吹毛求疵者:我知道,即使在C# 1中,也可以编写强类型的枚举器(就像List<T>那样);绝大多数情况下并非如此。
那时,如果您不小心将错误的类型放入foreach中,您更愿意让它抛出异常,而不是神秘地什么也不做。
正如JaredPar所解释的,您应该使用OfType方法。
https://stackoverflow.com/questions/1439516
复制相似问题