yield---迭代集合的不同方式-创新互联
yield return 语句返回集合的一个元素

yield break 可停止迭代
------------------------------------------------------------------Student.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication3
{
public class Student
{
string[] str = new string[] { "张飞", "关羽", "贝贝", "香香" };
///
/// 正序迭代
///
///
public IEnumerator GetEnumerator()
{
for (int i = 0; i < str.Length; i++)
{
yield return str[i];
}
}
///
/// 倒序迭代
///
///
public IEnumerable Reverse()
{
for (int i = str.Length-1; i >= 0; i--)
{
yield return str[i];
}
}
///
/// 自定义迭代
///
/// 开始索引
/// 长度
///
public IEnumerable Subset(int index, int length)
{
for (int i = index; i < index+length; i++)
{
yield return str[i];
}
}
}
} ------------------------------------------------------------------主程序
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
Student s = new Student();
foreach (var item in s)//正序迭代
{
Console.WriteLine(item);
}
Console.WriteLine("reverse");
foreach (var item in s.Reverse())//倒序迭代
{
Console.WriteLine(item);
}
Console.WriteLine("subset");//自定义迭代
foreach (var item in s.Subset(1,1))
{
Console.WriteLine(item);
}
Console.ReadKey();
}
}
}创新互联www.cdcxhl.cn,专业提供香港、美国云服务器,动态BGP最优骨干路由自动选择,持续稳定高效的网络助力业务部署。公司持有工信部办法的idc、isp许可证, 机房独有T级流量清洗系统配攻击溯源,准确进行流量调度,确保服务器高可用性。佳节活动现已开启,新人活动云服务器买多久送多久。
网站标题:yield---迭代集合的不同方式-创新互联
本文链接:http://www.jxjierui.cn/article/dopiej.html


咨询
建站咨询
