C# 通过IEnumerable枚举Com对象集合

C# 通过IEnumerable枚举Com对象集合,c#,collections,com,outlook,C#,Collections,Com,Outlook,我想通过方法迭代Outlook.Selection(实现IEnumerable的集合)或Outlook.Items集合(也间接实现IEnumerable)。因此,方法参数可以是其中之一 我不知道如何正确地实现该方法的参数。 到目前为止,我认为: Outlook.Selection items1 = activeExplorer.Selection; Outlook.Items items2 = currentFolder.Items; // How can i input these as p

我想通过方法迭代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)
            {
                //...
            }
        }
Outlook.Selection items1=activeExplorer.Selection;
Outlook.Items items2=currentFolder.Items;
//如何将这些作为参数输入到下面的方法中?
//到目前为止,迭代的方法如下所示:
私有void MethodX(IEnumerable items)
{
foreach(项目中的var项目)
{
//...
}
}
我不知道这是否是可能的,因为使用COM对象。。。
也许还有别的办法

回答上面的评论-要使用“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);  
}
Outlook.Items项目2=currentFolder.Items;

对于(int i=1;i)如果它们实现了
IEnumerable
,那么您可以使用
.Cast
这不起作用:MethodX(selection.Cast());您必须强制转换到集合元素类型,而不是集合类型。根据所选内容,哪种类型可以是其中之一,因此您可能更喜欢of type()相反。只是为了记录,枚举items集合中的所有项是一个坏主意。要么使用items集合的子集(Find/FindNext/Restrict),要么使用“for”循环,并在每次迭代结束时显式释放每个项。如果使用“for”循环,则您将无法使用枚举器。并且您必须释放循环中的所有项,以避免耗尽RPC通道。