方法一
可以通过申明一个迭代器的属性实现迭代器
方法是
<访问控制符> IEnumerable
<T> 迭代器名称
每次访问迭代器,会从老地方进入迭代器函数,然后迭代器 yield
或终止,下次再从 yield
的下一行开始执行。
如果迭代器函数已经结束,不需要返回任何东西,foreach
会结束对其的访问。
using System.Text;
namespace ConsoleApp1
{
class Class2
{
static void Main()
{
foreach (string word in WordSequence(" @Fuck,you, leatherman!"))
{
Console.WriteLine(word);
}
Console.ReadKey();
}
public static IEnumerable<string> WordSequence(string str)
{
StringBuilder newWord = new StringBuilder(20);
int status = 0;
for (int i = 0; i < str.Length; i++)
{
if ((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z')) {
status = 1;
newWord.Append(str[i]);
}
else if (status == 1)
{
yield return newWord.ToString();
newWord.Clear();
status = 0;
}
}
if (newWord.Length > 0)
{
yield return newWord.ToString();
}
}
}
}
Outputs:
Fuck
you
leather
man
附:
1. C# 有和 Java 类似的 StringBuilder
。
2. string 的字符通过 str[i]
下标访问。
方法2
实现IEnumerable接口,需要实现GetEmumerator方法
static void Main()
{
DaysOfTheWeek days = new DaysOfTheWeek();
foreach (string day in days)
{
Console.Write(day + " ");
}
// Output: Sun Mon Tue Wed Thu Fri Sat
Console.ReadKey();
}
public class DaysOfTheWeek : IEnumerable
{
private string[] days = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
public IEnumerator GetEnumerator()
{
for (int index = 0; index < days.Length; index++)
{
// Yield each day of the week.
yield return days[index];
}
}
}