迭代 yield
时间:2010-09-02 来源:liangyammu
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace MyArray
{
class Program
{
static void Main(string[] args)
{
MyNames names = new MyNames();
Console.WriteLine("默认");
foreach (string name in names)
{
Console.WriteLine(name);
}
Console.WriteLine("倒序");
foreach (string name in names.Reverse())
{
Console.WriteLine(name);
}
Console.WriteLine("截取");
foreach (string name in names.Subset(2, 2))
{
Console.WriteLine(name);
}
Console.Read();
}
}
public class MyNames
{
string[] names = { "liang", "zhnag", "li", "chen" };
public IEnumerator GetEnumerator()
{
for (int i = 0; i < 4; i++)
{
yield return names[i];
}
}
public IEnumerable Reverse()
{
for (int i = 3; i >=0; i--)
{
yield return names[i];
}
}
/// <summary>
/// 用Subset()方法搜索迭代子集
/// </summary>
/// <param name="index">起始索引</param>
/// <param name="length">返回元素的个数</param>
/// <returns></returns>
public IEnumerable Subset(int index, int length)
{
for (int i = 0; i < index + length; i++)
{
yield return names[i];
}
}
}
}