【发布时间】:2009-10-20 21:01:49
【问题描述】:
在阅读帖子时,没有示例给出了一些分数:
要实现 IEnumerable / IEnumerable,你必须提供一个枚举器:
•如果类正在“包装”另一个集合,则返回被包装的集合的枚举数。
•通过使用 yield return 的迭代器。
•通过实例化您自己的 IEnumerator/IEnumerator 实现
(我的小脑袋把它解释为)
(第 1 点)
If the class is "wrapping" another collection, by returning the
wrapped collection's enumerator.
这意味着..
class StringCollections
{
//A class is wrapping another collection
string[] names=new string {“Jon Skeet”,”Hamish Smith”,
”Marc Gravell”,”Jrista”,”Joren”};
//by returning the wrapped collection’s enumerator
public IEnumerator GetEnumerator( )
{
// What should I return here ?
//like the following ?
yield return names[0];
yield return names[1];
yield return names[2];
....
(or)
foreach(string str in names)
{
yield return str;
}
}
}
(第 2 点)
•Via an iterator using yield return.(This point was well explained
by Marc Gravell)
第 3 点
By instantiating your own IEnumerator/IEnumerator<T> implementation*
第 3 点在这里代表什么?,因为没有例子,我没有得到那个。 这是否意味着,我可以构建自定义枚举器..(对吗?)。我的问题是预构建枚举器/枚举器何时足够(作为初学者,我不应该盲目地确认这一点) 我为什么要照顾自定义的迭代?很好的例子将澄清我的疑问。
感谢您阅读这篇冗长的故事和友好的回应。
【问题讨论】:
标签: c# collections enumeration