yield(C# 参考)
来源:互联网 发布:护士执业考试题库软件 编辑:程序博客网 时间:2024/05/22 13:17
在迭代器块中用于向枚举数对象提供值或发出迭代结束信号。它的形式为下列之一:
yield return <expression>;yield break;
备注
计算表达式并以枚举数对象值的形式返回;expression 必须可以隐式转换为迭代器的 yield 类型。
yield 语句只能出现在 iterator 块中,该块可用作方法、运算符或访问器的体。这类方法、运算符或访问器的体受以下约束的控制:
不允许不安全块。
方法、运算符或访问器的参数不能是 ref 或 out。
yield 语句不能出现在匿名方法中。有关更多信息,请参见匿名方法(C# 编程指南)。
当和 expression 一起使用时,yield return 语句不能出现在 catch 块中或含有一个或多个 catch 子句的 try 块中。有关更多信息,请参见异常处理语句(C# 参考)。
示例
在下面的示例中,迭代器块(这里是方法 Power(int number, int power))中使用了 yield 语句。当调用 Power 方法时,它返回一个包含数字幂的可枚举对象。注意 Power 方法的返回类型是 IEnumerable(一种迭代器接口类型)。
// yield-example.csusing System;using System.Collections;public class List{ public static IEnumerable Power(int number, int exponent) { int counter = 0; int result = 1; while (counter++ < exponent) { result = result * number; yield return result; } } static void Main() { // Display powers of 2 up to the exponent 8: foreach (int i in Power(2, 8)) { Console.Write("{0} ", i); } }}
2 4 8 16 32 64 128 256
- yield(C# 参考)
- yield(C# 参考)
- yield(C# 参考)
- yield(C# 参考)
- yield(C# 参考)
- yield(C# 参考)
- C# yield
- C# - yield
- c# yield
- C# Yield
- c# - yield
- C# yield
- C# yield
- C#基础知识(六)yield 关键字
- C# 参考之上下文关键字get、set、value、partial、where和yield
- C# 参考之上下文关键字get、set、value、partial、where和yield
- C# 参考之上下文关键字get、set、value、partial、where和yield
- switch(C# 参考)
- 我才刚刚开始
- 树形控件复选框的级联选择
- 初学者学习VC++的一点心得
- 本地虚拟机测试环境模拟
- 哦~原来我的号码使用的人那么多吗?
- yield(C# 参考)
- linux学习笔记(4)
- 艰难的Hyper-V Server 2008 R2 初上手
- M公司面试记
- 现在的大学生,实在太有勇气了--转
- 12.18(java中的view, ibatis dao)
- 程序员8小时以外的挣钱路子……
- VS2005开发常见错误及解决(1)VS2005调试程序出错,绑定句柄无效 Terminal Services
- 族谱考证:奥巴马应叫巴菲特“太爷爷”