我正在学习迭代器模式,当我遇到样例代码中的逻辑时有些困惑。
class MonthCollection : IEnumerable
{
public string[] months = {
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"};
public IEnumerator GetEnumerator()
{
// Generates values from the collection
foreach (string element in months)
yield return element;
}
}
static void Main()
{
MonthCollection collection = new MonthCollection();
// Consumes values generated from collection's GetEnumerator method
foreach (string n in collection)
Console.Write(n + " ");
Console.WriteLine("\n");
}
在这段代码中,访问数组字符串的常规方式是在foreach语句中调用months变量,如下所示: MonthCollection collection = new MonthCollection();
foreach (string n in collection.months){ } 但我不理解为什么foreach可以直接访问集合而不需要直接调用months变量。 MonthCollection collection = new MonthCollection();
foreach (string n in collection){} 更新1:
我不明白的是,在上述类中如何访问变量months而不是直接调用它。
static void Main()
{
MonthCollection collection = new MonthCollection();
// Consumes values generated from collection's GetEnumerator method
foreach (string n in collection.months)
Console.Write(n + " ");
Console.WriteLine("\n");
}
不是像这样
MonthCollection collection = new MonthCollection();
method
foreach (string n in collection)
Console.Write(n + " ");
Console.WriteLine("\n");
in
右侧的对象必须是IEnumerable
的实现,否则会在编译时出错。foreach
通过调用GetEnumerator()
获取枚举器,因为它知道类型检查已经成功。这是C#中使用库定义的类进行代码生成的一部分“魔法”。 - Sergey KalinichenkoIEnumerable
就可以在foreach
中使用。只需具有public TSomething GetEnumerator()
,其中TSomething
具有public TElement Current { get; }
和public bool MoveNext()
即可让foreach
正常工作。 - user4003407