7,540
社区成员
发帖
与我相关
我的任务
分享
ref class Enumerator : System::Collections::Generic::IEnumerator<ItemType>, System::IDisposable
{
private:
ItemCollection<ItemType>^ m_List;
System::Int32 m_Index;
System::Int32 m_Version;
ItemType m_Current;
public:
Enumerator(ItemCollection<ItemType>^ list)
{
this->m_List=list;
this->m_Index=0;
this->m_Version=list->m_Version;
this->m_Current=ItemType();
}
virtual System::Boolean MoveNext()
{
ItemCollection<ItemType>^ list = this->m_List;
if ((this->m_Version == list->m_Version) && (this->m_Index < list->m_Size))
{
this->m_Current = list->m_InnerArray[this->m_Index];
this->m_Index++;
return true;
}
if (this->m_Version != list->m_Version)
{
throw gcnew System::InvalidOperationException("集合已改变,操作无效");
}
this->m_Index = this->m_List->m_Size + 1;
this->m_Current = ItemType();
return false;
}
//1
property virtual System::Object^ Current
{
System::Object^ get(){return this->m_Current;}
}
property virtual ItemType Current
{
ItemType get()
{
return this->m_Current;
}
}
virtual void Reset()
{
this->m_Index = 0;
this->m_Current = ItemType();
}
~Enumerator()
{
}
property virtual ItemType Current
{
ItemType get(){return this->m_Current;}
}
// 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);
}