1.yield语句有两种形式
(1)yield return ;一次返回一个元素
运行yield return 语句时,会返回一个 值,并记录当前位置及保留该值。下次调用迭代器函数时,将从该位置重新开始执行
(2)yield break;终止迭代
2.迭代器声明
(1) 返回类型必须为 IEnumerable、IEnumerable、IEnumerator 或 IEnumerator,或者IEnumerable、IEnumerator 的继承类
(2)声明不能有任何 in、ref 或 out 参数
3.yield关键字使用缺点
(1)匿名方法不能包含 yield return 或 yield break 语句
(2)被unsafe(不安全)修饰的方法不能使用yield关键字
4.异常处理
(1)yield return语句不能置于try-catch块,既不能放在try块也不能放在catch块
(2)yield return 语句可以置于try-finally语句try块,能放在try块但不能放在finally块
(3)yield break语句可以置于try块和catch块,不能置于finally块
(4)如果 foreach 主体(在迭代器方法之外)引发异常,则将执行迭代器方法中的 finally 块
5.打印集合中的元素
(1)直接打印集合中的元素
static void Main(string[] args)
{foreach (var item in GetMultiplyNoYield(2,8))
{
Console.WriteLine("{0}", item);
}
Console.ReadKey();
}///
///不使用yield///
///
///
///
public static IEnumerable GetMultiplyNoYield(int number,intexponent)
{
List list = new List();int result = 1;for (int i = 0; i < exponent; i++)
{
result= result *number;
list.Add(result);
}returnlist;
}
(2)使用yield简化版
static void Main(string[] args)
{foreach (var item in GetMultiplyHasYield(2, 8))
{
Console.WriteLine("{0}", item);
}
Console.ReadKey();
}///
///使用yield///
///
///
///
private static IEnumerable GetMultiplyHasYield(int number,intexponent)
{int result = 1;for (int i = 0; i < exponent; i++)
{
result= result *number;yield returnresult;
}
}