如何:使用 for each 循环访问泛型集合
泛型 (Visual C++) Visual C++ 功能允许您创建泛型集合。
示例
此示例演示如何使用简单的泛值类型集合的 for each。
// for_each_generics.cpp
// compile with: /clr
using namespace System;
using namespace System::Collections::Generic;
generic <class T>
public value struct MyArray : public IEnumerable<T> {
MyArray( array<T>^ d ) {
data = d;
}
ref struct enumerator : IEnumerator<T> {
enumerator( MyArray^ myArr ) {
colInst = myArr;
currentIndex = -1;
}
virtual bool MoveNext() = IEnumerator<T>::MoveNext {
if ( currentIndex < colInst->data->Length - 1 ) {
currentIndex++;
return true;
}
return false;
}
virtual property T Current {
T get() {
return colInst->data[currentIndex];
}
};
property Object^ CurrentNonGeneric {
virtual Object^ get() = System::Collections::IEnumerator::Current::get {
return colInst->data[currentIndex];
}
};
virtual void Reset() {}
~enumerator() {}
MyArray^ colInst;
int currentIndex;
};
array<T>^ data;
virtual IEnumerator<T>^ GetEnumerator() {
return gcnew enumerator(*this);
}
virtual System::Collections::IEnumerator^ GetEnumeratorNonGeneric() = System::Collections::IEnumerable::GetEnumerator {
return gcnew enumerator(*this);
}
};
int main() {
MyArray<int> col = MyArray<int>( gcnew array<int>{10, 20, 30 } );
for each ( Object^ c in col )
Console::WriteLine((int)c);
}