C#Strange Index Out Of Bounds异常

时间:2015-02-01 17:26:57

标签: c# outlook indexoutofboundsexception

在调试我正在为MS Outlook 2010开发的插件时,我遇到了一个奇怪的问题,因为我有一个类来进行消息处理。在该类的构造函数中,我传递了一个MailItem。然后,我打算运行MailItem的“收件人”列表,并查找在“收件人”,“抄送”和“密件抄送”字段中注册的所有收件人。为此,我有以下代码:

public MessageProcessor(Outlook.MailItem theMail)
{
  _activeMailItem = theMail;
  _activeMailDetails.Sender = theMail.SenderEmailAddress;
  if (_activeMailItem.Recipients.Count > 0)
  {
    List<string> recipients = new List<string>();
    List<string> cc = new List<string>();
    List<string> bcc = new List<string>();
    for (int i = 0; i < _activeMailItem.Recipients.Count; i++)
    {
      switch (_activeMailItem.Recipients[i].Type)    <----- HERE
      {
        case (int)Outlook.OlMailRecipientType.olTo:
           recipients.Add(_activeMailItem.Recipients[i].Address);
           break;
        case (int)Outlook.OlMailRecipientType.olCC:
           cc.Add(_activeMailItem.Recipients[i].Address);
           break;
        case (int)Outlook.OlMailRecipientType.olBCC:
           bcc.Add(_activeMailItem.Recipients[i].Address);
           break;
      }
    }
  }
}

但是,我在标有“HERE”的点上得到例外。当我调试并查看Recipients.Count属性的值时,它显示1.但是,当“i”索引为0(应该是有效索引 - 并且在这种情况下,唯一有效的索引)时会出现问题)。当我尝试查看_activeMailItem.Recipients集合时,我看到Count为1;然而,当我试图在结构中进一步向下追踪时,我看到一些红色十字架,我无法检查下面的值。

有没有人知道可能出现什么问题?

提前致谢。

1 个答案:

答案 0 :(得分:7)

Outlook中的所有馆藏(包括收件人)均为1,而不是0:

for (int i = 1; i <= _activeMailItem.Recipients.Count; i++)