1. foreach语句
c#编译器会把foreach语句转换为ienumerable接口的方法和属性。
foreach (person p in persons)
{
console.writeline(p);
}
foreach语句会解析为下面的代码段。
•调用getenumerator()方法,获得数组的一个枚举
•在while循环中,只要movenext()返回true,就一直循环下去
•用current属性访问数组中的元素
ienumerator enumerator = persons. getenumerator();
while (enumerator.movenext())
{
person p = (person) enumerator.current;
console.writeline(p);
}
2. yield语句
•yield语句的两种形式:
yield return <expression>;
yield break;
•使用一个yield return语句返回集合的一个元素
•包含yield语句的方法或属性是迭代器。迭代器必须满足以下要求
a. 返回类型必须是ienumerable、ienumerable<t>、ienumerator或 ienumerator<t>。
b. 它不能有任何ref或out参数
•yield return语句不能位于try-catch快。yield return语句可以位于try-finally的try块
try
{
// error: cannot yield a value in the boday of a try block with a catch clause
yield return "test";
}
catch
{ }
try
{
//
yield return "test again";
}
finally
{ }
try
{ }
finally
{
// error: cannot yield in the body of a finally clause
yield return "";
}
yield break语句可以位于try块或catch块,但是不能位于finally块
下面的例子是用yield return语句实现一个简单集合的代码,以及用foreach语句迭代集合
using system;
using system.collections.generic;
namespace consoleapplication6
{
class program
{
static void main(string[] args)
{
hellocollection hellocollection = new hellocollection();
foreach (string s in hellocollection)
{
console.writeline(s);
console.readline();
}
}
}
public class hellocollection
{
public ienumerator<string> getenumerator()
{
// yield return语句返回集合的一个元素,并移动到下一个元素上;yield break可以停止迭代
yield return "hello";
yield return "world";
}
}
}
使用yield return语句实现以不同方式迭代集合的类:
using system;
using system.collections.generic;
namespace consoleapplication8
{
class program
{
static void main(string[] args)
{
musictitles titles = new musictitles();
foreach (string title in titles)
{
console.writeline(title);
}
console.writeline();
foreach (string title in titles.reverse())
{
console.writeline(title);
}
console.writeline();
foreach (string title in titles.subset(2, 2))
{
console.writeline(title);
console.readline();
}
}
}
public class musictitles
{
string[] names = { "a", "b", "c", "d" };
public ienumerator<string> getenumerator()
{
for (int i = 0; i < 4; i++)
{
yield return names[i];
}
}
public ienumerable<string> reverse()
{
for (int i = 3; i >= 0; i--)
{
yield return names[i];
}
}
public ienumerable<string> subset(int index, int length)
{
for (int i = index; i < index + length; i++)
{
yield return names[i];
}
}
}
}
输出:
如对本文有疑问,
点击进行留言回复!!
相关文章:
-
-
-
C#实现猜数字游戏
本文实例为大家分享了c#实现猜数字游戏具体代码,供大家参考,具体内容如下给定一个0-100的随机数字猜其大小题目样式:电脑产生一个0到100之间的随机数字,并且...
[阅读全文]
-
-
C# 可空类型的具体使用
在项目中我们经常会遇到可为空类型,那么到底什么是可为空类型呢?下面我们将从4个方面为大家剖析。1、可空类型基础知识顾名思义,可空类型指的就是某个对象类型可以为空...
[阅读全文]
-
-
-
C#实现猜数字小游戏
本文实例为大家分享了c#实现猜数字小游戏的具体代码,供大家参考,具体内容如下效果如图:代码:using system;using system.collecti...
[阅读全文]
-
-
C#实现简单俄罗斯方块
最近在看《.net游戏编程入门经典 c#篇》 第一章介绍了如何制作俄罗斯方块,自己试了试按照书上的步骤,可算是完成了。于是写下这篇文章留作纪念。1.类的设计在充...
[阅读全文]
-
网友评论