簡體   English   中英

收益不適用於自定義枚舉/枚舉器

[英]yield not working with custom enumerable/enumerator

最近,我開始了一個業余項目來重寫collections結構,首先刪除了不通用的IEnumeratorIEnumerable ,從而創建了新的IEnumerator / IEnumerable基本接口。 在新的可枚舉接口和普通接口之間創建轉換時,我很快遇到了收益問題。

我的IEnumerable<T>IEnumerator<T>與普通的完全相同,只是它們不從非通用的繼承。 為什么yield無法與我的界面一起使用? 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
    }
}

您的foreach之所以有效,是因為foreach使用鴨式輸入法 -任何具有GetEnumerator方法的方法都可以使用。 這是因為foreach比泛型更早,因此這是實現它並獲得強類型化的唯一合理方法。

但是,迭代器方法並不比泛型更老,因此在設計yield要考慮IEnumerable<T> 因此, yield 要求

  • 返回類型必須為IEnumerableIEnumerable<T>IEnumeratorIEnumerator<T>

https://msdn.microsoft.com/zh-cn/library/9k7k7cf0.aspx

當然,您自己構建的可枚舉類不在列表中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM