У кого-нибудь есть рабочий, пошаговый пример того, как реализовать IEnumerable и IEnumerator в C ++ / CLI? В качестве альтернативы, кто-нибудь знает, как исправить следующий код из MS Connect, который не компилируется в Visual Studio 2005?
using namespace System;
using namespace System::Collections::Generic;
generic
public ref struct MyArray : public IEnumerable
{
MyArray( array^ d )
{
data = d;
}
ref struct enumerator : IEnumerator
{
enumerator( MyArray^ myArr )
{
colInst = myArr;
currentIndex = -1;
}
bool MoveNext()
{
if( currentIndex < colInst->data->Length - 1 )
{
currentIndex++;
return true;
}
return false;
}
property T Current
{
T get()
{
return colInst->data[currentIndex];
}
};
// This is required as IEnumerator also implements IEnumerator
property Object^ Current2
{
virtual Object^ get() new sealed = System::Collections::IEnumerator::Current::get
{
return colInst->data[currentIndex];
}
};
void Reset() {}
~enumerator() {}
MyArray^ colInst;
int currentIndex;
};
array^ data;
IEnumerator^ GetEnumerator()
{
return gcnew enumerator(this);
}
virtual System::Collections::IEnumerator^ GetEnumerator2() new sealed = System::Collections::IEnumerable::GetEnumerator
{
return gcnew enumerator(this);
}
};
int main()
{
int retval = 0;
MyArray^ col = gcnew MyArray( gcnew array{10, 20, 30 } );
for each( Object^ c in col )
{
retval += (int)c;
}
retval -= 10 + 20 + 30;
Console::WriteLine("Return Code: {0}", retval );
return retval;
}
Компилятор не может найти реализации метода перечислителя:
error C3766: 'MyArray::enumerator' must provide an implementation for the interface method 'bool System::Collections::IEnumerator::MoveNext(void)' c:\Projects\VCNET\2005\IEnumerable\IEnumerable\IEnumerable.cpp 55
error C3766: 'MyArray::enumerator' must provide an implementation for the interface method 'void System::Collections::IEnumerator::Reset(void)' c:\Projects\VCNET\2005\IEnumerable\IEnumerable\IEnumerable.cpp 55
error C3766: 'MyArray::enumerator' must provide an implementation for the interface method 'T System::Collections::Generic::IEnumerator::Current::get(void)' c:\Projects\VCNET\2005\IEnumerable\IEnumerable\IEnumerable.cpp 55
error C3766: 'MyArray' must provide an implementation for the interface method 'System::Collections::Generic::IEnumerator ^System::Collections::Generic::IEnumerable::GetEnumerator(void)' c:\Projects\VCNET\2005\IEnumerable\IEnumerable\IEnumerable.cpp 68