How to: 反覆運算泛型集合與每個
泛型 (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);
}