yield无法使用自定义枚举/枚举器

gbi*_*ing -1 c# yield

最近我开始了一个业余爱好项目来重写集合结构,首先删除非泛型,IEnumeratorIEnumerable创建新的IEnumerator/IEnumerable基接口.当我在新的可枚举界面和正常界面之间创建转换时,我很快就遇到了产量问题.

IEnumerable<T>IEnumerator<T>正常的一样,除了它们不从非通用的继承.为什么不能使用我的接口?foreach可以使用我的界面.

例:

public static System.Collections.Generic.IEnumerable<T> ToMSEnumerable(this My.IEnumerable<T> enumerable)
{
    foreach (var item in enumerable) // enumerating my enumerable works
    {
        yield return item; // this works
    }
}

public static My.IEnumerable<T> ToMyEnumerable(this System.Collections.Generic.IEnumerable<T> enumerable)
{
    foreach (var item in enumerable) // obviously work
    {
        yield return item; // this is where its not working.
                           // I haven't touched this in a few day, so I don't remember
                           // the error message
    }
}
Run Code Online (Sandbox Code Playgroud)

Blo*_*ard 7

你的foreach作品因为foreach使用鸭子打字 - 任何GetEnumerator方法都可以.这是因为foreach它比泛型更旧,所以这是实现它并获得强类型的唯一合理方式.

但是,迭代器方法并不比泛型更老,因此yield在设计时IEnumerable<T>考虑到了这一点.因此,yield 要求:

  • 返回类型必须是IEnumerable,IEnumerable<T>,IEnumerator,或IEnumerator<T>.

(https://msdn.microsoft.com/en-us/library/9k7k7cf0.aspx)

当然,您自己构建的可枚举类不在列表中.