且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

实现IEnumerable< T>在C ++ / CLI中

更新时间:2022-03-13 15:02:35

您必须提供 the非通用GetEnumerator()方法,并包含非通用名称空间:

You must provide an explicit implementation of the non-generic GetEnumerator() method and include the non-generic namespace:

using namespace System::Collections;

....

virtual IEnumerator^ EnumerableGetEnumerator() = IEnumerable::GetEnumerator
{
    return GetEnumerator<MyClass^>();
}

更新:如评论中所述, GetEnumerator的显式版本必须命名为不同名称以避免名称冲突,因此我将其命名为EnumerableGetEnumerator。

Update: As mentioned in the comments, the explicit version of GetEnumerator must be named different to avoid name ***, thus I've named it EnumerableGetEnumerator.

类似地,在C#中,您必须这样做: / p>

Similarly, in C# you would have to do it like this:

using System.Collections.Generic;

public class MyCollection : IEnumerable<MyClass>
{
    public MyCollection()
    {
    }  

    public IEnumerator<MyClass> GetEnumerator()
    {
        return null;
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator<MyClass>();
    }
}