avatar

目录
C# yield关键字的用法

C# yield关键字的用法

yield关键字的作用是将当前集合中的元素立即返回。

1.返回元素用yield return;(一次一个的返回)

2.结束返回用yield break;(终止迭代)

3.返回类型必须为 IEnumerable、IEnumerable、IEnumerator 或 IEnumerator

4.参数前不能使用ref和out关键字

5.匿名方法中 不能使用yield

6.unsafe中不能使用

7.不能将 yield return 语句置于 try-catch 块中。 可将 yield return 语句置于 try-finally 语句的 try 块中。yield break 语句可以位于 try 块或 catch 块,但不能位于 finally 块。

Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

public IEnumerable Method()
{
List results = new List();
int counter = 0;
int result = 1;

while (counter++ < 10)
{
result = result * 2;
results.Add(result);
}
return results;
}

#通过 yield可以简化为:

public IEnumerable YieldDemo()
{
int counter = 0;
int result = 1;
while (counter++ < 10)
{
result = result * 2;
yield return result;
}
}

参考:

《C#中的yield关键字》

《C# 中的”yield”使用》

《MSDN的官方yield》

文章作者: HJY
文章链接: https://hjy-dev.github.io/2019/04/14/C-yield%E5%85%B3%E9%94%AE%E5%AD%97%E7%9A%84%E7%94%A8%E6%B3%95/
版权声明: 本博客所有文章除特别声明外,均采用 Apache License 2.0 许可协议。转载请注明来自 Kiven Blog
打赏
  • 微信
    微信
  • 支付寶
    支付寶

评论