VB6到C#:IUnknown

问题描述:

我有一个VB6属性,我试图转换为C#。这是因为如下:VB6到C#:IUnknown

Public Property Get NewEnum() As IUnknown 
    'this property allows you to enumerate 
    'this collection with the For...Each syntax 
    Set NewEnum = m_coll.[_NewEnum] 
End Property 

m_coll是私有变量,现在是一个ArrayList,而不是以前Collection

m_coll正在填充我自己的类对象之一。如您所见,此属性的类型为IUnknown

在这一点上,我可能只是没有正确思考,但是在C#中有这样的属性吗?

+0

你在想的IEnumerable的?这允许您在集合上使用foreach语句。 – 2013-04-09 20:04:35

+7

你不应该使用'ArrayList'。改为使用通用的'List '。 – Servy 2013-04-09 20:05:31

如果你希望能够在课上做一个foreach(如你可以通过在VB6暴露NewEnum()作为IUnknown的),你可以有你的类实现IEnumerable - 如:

public class MyClass : IEnumerable 
    { 
     private List<string> items = new List<string>(); 

     public MyClass() 
     { 
      items.Add("first"); 
      items.Add("second"); 
     } 


     public IEnumerator GetEnumerator() 
     { 
      return items.GetEnumerator(); 
     } 
    } 

这将使您可以使用这样的:

MyClass myClass =new MyClass(); 
      foreach (var itm in myClass) 
      { 
       Console.WriteLine(itm); 
      } 

我用List<string>为了简单,但你可以使用List<yourCustomClass>

+1

你已经找到答案后回答,但我仍会告诉你;)谢谢! – 2013-04-09 20:52:14

+0

谢谢!对不起,我没有更快:) – NDJ 2013-04-09 20:53:35