我有一个 Outlook 2013 加载项,
Outlook.MAPIFolder inboxFolder;
Outlook.Items mailInboxItems;
private void ThisAddIn_Startup(object sender, EventArgs e)
{
... other code ---
mailInboxItems = inboxFolder.Items;
mailInboxItems.ItemAdd += mailInboxItems_ItemAdd;
}
private void mailInboxItems_ItemAdd(object item)
{
Outlook.MailItem emailMessage = (Outlook.MailItem)item; // cast error
ProcessEmail(emailMessage);
}
当然,当传入的项目不是 Outlook.MailItem 类型时,将引发异常:
Unable to cast COM object of type 'System.__ComObject' to interface type 'Microsoft.Office.Interop.Outlook.MailItem'.
如何检查参数“item”是否仅为有效类型,即 Outlook.MailItem 以避免任何异常?
请您参考如下方法:
您可以在 C# 中使用“is”和“as”运算符。参见 How to: Programmatically Determine the Current Outlook Item获取更多信息。
Outlook 对象模型还提供了 MessageClass property - 表示 Outlook 项目的消息类的字符串。在幕后,消息类用于标识在 Outlook 中使用哪个检查器来显示项目。
