【问题标题】:Enumerate Com-Object Collections via IEnumerable通过 IEnumerable 枚举 Com-Object 集合
【发布时间】:2015-08-17 03:24:25
【问题描述】:

我想通过一个方法迭代一个 Outlook.Selection(它是一个实现 IEnumerable 的集合)或一个 Outlook.Items 集合(它也间接实现 IEnumerable)。所以方法参数可能是其中之一。

我不知道如何正确实现该方法的参数。 我到目前为止:

Outlook.Selection items1 = activeExplorer.Selection;
Outlook.Items items2 = currentFolder.Items;

// How can i input these as parameter into the method below?

// The Method to iterate looks like this so far:
        private void MethodX<T>(IEnumerable<T> items)
        {
            foreach (var item in items)
            {
                //...
            }
        }

我不知道这是否可能因为使用 COM-Objects... 也许还有其他方法?!

【问题讨论】:

  • 如果他们实现了IEnumerable,那么你可以使用.Cast&lt;T&gt;
  • 这不起作用:MethodX(selection.Cast());
  • 您必须强制转换为集合元素类型,而不是集合类型。哪个可以是many possible interfaces 之一,具体取决于选择的内容,因此您可能更喜欢 OfType()。
  • 只是为了记录,枚举 Items 集合中的 所有 项是一个坏主意。要么使用 Items 集合的子集(Find/FindNext/Restrict),要么使用“for”循环并在每次迭代结束时显式释放每个项目。
  • 如果您使用“for”循环,那么您将无法使用枚举器。并且您必须释放循环内的所有项目以避免耗尽 RPC 通道。

标签: c# collections com outlook


【解决方案1】:

回复上面的评论 - 要使用“for”循环,请尝试以下操作:

Outlook.Items items2 = currentFolder.Items;
for (int i = 1; i <= items2.Count; i++)
{
  object item = items2[i];
  Outlook.MailItem mailItem = (MailItem)item;
  if (mailItem != null) //you can have objects other than MailItem
  {
    //use mailItem here
    Marshal.ReleaseComObject(mailItem );
  }
  Marshal.ReleaseComObject(item);  
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-21
    • 1970-01-01
    • 1970-01-01
    • 2013-01-10
    • 1970-01-01
    • 2016-07-28
    • 1970-01-01
    相关资源
    最近更新 更多