C#中foreach遍历学习笔记

时间:2023-03-09 03:38:48
C#中foreach遍历学习笔记
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace ForeachDemo
{
class Program
{
static void Main()
{
Mylist list = new Mylist();
MyList2 list2 = new MyList2();
foreach (string str in list)
{
Console.WriteLine(str);
}
Console.WriteLine("==========================================");
foreach (string str in list2)
{
Console.WriteLine(str);
}
}
} class Mylist : IEnumerable //通过yield return 来返回,实现IEnumerable接口
{
static string[] testString= { "", "", "", "" ,""}; public IEnumerator GetEnumerator()
{
foreach (string str in testString)
{
yield return str;
}
}
} class MyList2 : IEnumerable //实现自己的IEnumerator来实现
{
static string[] testString2 = { "", "", "", "", "" };
public IEnumerator GetEnumerator()
{
return new MyEnumerator();
}
private class MyEnumerator : IEnumerator
{
int index = -;
public object Current
{
get
{
return testString2[index];
}
} public bool MoveNext()
{
if (++index >= testString2.Length)
{
return false;
}
else
{
return true;
}
} public void Reset()
{
index = -;
} }
} }

参考:

http://www.cnblogs.com/jesse2013/p/CollectionsInCSharp.html

http://www.cnblogs.com/kingcat/archive/2012/07/11/2585943.html