[英]C# Generic IEnumerable
我正在了解引擎蓋下的迭代器模式,因此最終我可以在某些類中使用它。 這是一個測試班:
public class MyGenericCollection : IEnumerable<int>
{
private int[] _data = { 1, 2, 3 };
public IEnumerator<int> GetEnumerator()
{
foreach (int i in _data)
{
yield return i;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
我對IEnumerable.GetEnumerator()
部分感到困惑。 在我運行的代碼測試中,從未引用或使用過它,但我必須使用它來實現通用IEnumerable
。
我確實了解IEnumerable<T>
繼承自IEnumerator
,因此我必須實現兩者。
除此之外,我曾經使用過非通用接口時感到困惑。 在調試中,它永遠不會輸入。 誰能幫我理解?
我對IEnumerable.GetEnumerator()部分感到困惑。 在我運行的代碼測試中,從未引用或使用過它,但我必須使用它來實現通用IEnumerable。
任何將您的類型用作IEnumerable
都將使用它。 例如:
IEnumerable collection = new MyGenericCollection();
// This will call the GetEnumerator method in the non-generic interface
foreach (object value in collection)
{
Console.WriteLine(value);
}
也只有少數LINQ方法可以調用它: Cast
和OfType
:
var castCollection = new MyGenericCollection().OfType<int>();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.