1.是不是由于2.0之前没有提供迭代器所以才继承IEnumerable接口,因为我发现实现它还是比较麻烦的;
2.现在有了迭代器是不是可以不用继承IEnumerable接口啦?我只要符合它的签名就可以在foreach循环中试用,不用实现IEnumerable与IEnumerator接口啦!
3.是不是迭代器与IEnumerable是相同的功能。
请说详细点。
2.现在有了迭代器是不是可以不用继承IEnumerable接口啦?我只要符合它的签名就可以在foreach循环中试用,不用实现IEnumerable与IEnumerator接口啦!
3.是不是迭代器与IEnumerable是相同的功能。
请说详细点。
迭代器是可以返回相同类型的值的有序序列的一段代码。迭代器可用作方法、运算符或 get 访问器的代码体。迭代器代码使用 yield return 语句依次返回每个元素。yield break 将终止迭代。有关更多信息,请参见 yield。可以在类中实现多个迭代器。每个迭代器都必须像任何类成员一样有唯一的名称,并且可以在 foreach 语句中被客户端代码调用,如下所示:foreach(int x in SampleClass.Iterator2){}迭代器的返回类型必须为 IEnumerable、IEnumerator、IEnumerable<T> 或 IEnumerator<T>。yield 关键字用于指定返回的值。到达 yield return 语句时,会保存当前位置。下次调用迭代器时将从此位置重新开始执行。迭代器对集合类特别有用,它提供一种简单的方法来迭代不常用的数据结构(如二进制树)。例
在本示例中,DaysOfTheWeek 类是将一周中的各天作为字符串进行存储的简单集合类。foreach 循环每迭代一次,都返回集合中的下一个字符串。C# 复制代码
public class DaysOfTheWeek : System.Collections.IEnumerable
{
string[] m_Days = { "Sun", "Mon", "Tue", "Wed", "Thr", "Fri", "Sat" }; public System.Collections.IEnumerator GetEnumerator()
{
for (int i = 0; i < m_Days.Length; i++)
{
yield return m_Days[i];
}
}
}class TestDaysOfTheWeek
{
static void Main()
{
// Create an instance of the collection class
DaysOfTheWeek week = new DaysOfTheWeek(); // Iterate with foreach
foreach (string day in week)
{
System.Console.Write(day + " ");
}
}
}
public class A: System.Collections.IEnumerable
{
string[] v = { "1”,“2”,“3”,“4”,“5”,“6" };
public static System.Collections.IEnumerator GetEnumerator()
{
for (int i = 0; i < v.Length; i++)
{
yield return v[i];
}
}
}
while (Test.GetEnumerator().MoveNext())
{
string obj = (string)ee.Current;
System.Console.WriteLine(obj);
}
//第二种
foreach (string obj1 in Test.GetEnumerator())
{
System.Console.WriteLine(obj1);
}
参考
http://www.cnblogs.com/soundbbg/articles/1277027.html
http://www.cnblogs.com/miclu/articles/945842.html
我理解了。