如何:使用 for each 循环访问用户定义集合

对于托管集合的类,它需要一个非私有 GetEnumerator 函数,返回一个句柄到枚举器类或接口。枚举器类必须包含非静态 MoveNext 函数和当前属性的声明。

示例

使用引用类型的简单用户定义的集合。

// for_each_user_defined_collections.cpp
// compile with: /clr
using namespace System;
public interface struct IMyEnumerator {
   bool MoveNext();
   property Object^ Current {
      Object^ get();
   }
   void Reset();
};

public ref struct MyArray {   
   
   MyArray( array<int>^ d ) {
      data = d;
   }

   ref struct enumerator : IMyEnumerator {
      enumerator( MyArray^ myArr ) {
         colInst = myArr;
         currentIndex = -1;
      }

      virtual bool MoveNext() {
         if( currentIndex < colInst->data->Length - 1 ) {
            currentIndex++;
            return true;
         }
         return false;
      }
   
      property Object^ Current {
         virtual Object^ get() {
            return colInst->data[currentIndex];
         }
      };
      
      virtual void Reset() {}
      ~enumerator() {}
         
      MyArray^ colInst;
      int currentIndex;
   };
   
   array<int>^ data;

   IMyEnumerator^ GetEnumerator() {
      return gcnew enumerator(this);
   }
};

int main() {
   int retval = 0;

   MyArray^ col = gcnew MyArray( gcnew array<int>{10, 20, 30 } );
   
   for each ( Object^ c in col )
      retval += (int)c;

   retval -= 10 + 20 + 30;
   
   for each ( int c in gcnew MyArray( gcnew array<int>{10, 20, 30 } ) )
      retval += c;

   retval -= 10 + 20 + 30;
   
   Console::WriteLine("Return Code: {0}", retval );
   return retval;
}
  

请参见

参考

for each,in