【发布时间】:2017-03-12 17:39:04
【问题描述】:
我正在经历迭代器模式,当我偶然发现示例代码中的逻辑时有点困惑
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 语句中像这样调用月份变量
MonthCollection 集合 = new MonthCollection();
foreach(collection.months 中的字符串 n){ }
但我不明白 foreach 是如何访问 甚至不直接调用months变量的集合
MonthCollection 集合 = new MonthCollection();
foreach(集合中的字符串 n){}
更新 1
我无法理解的是如何访问变量月份而不在上面的类中这样调用它
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");
【问题讨论】:
标签: c# collections foreach iterator