How to: 反覆運算具有使用者定義的集合,每個
類別可以是受管理的集合,它必須傳回列舉值類別或介面的控制碼的非私用 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;
}