yield return关键字怎么使用?
生活随笔
收集整理的這篇文章主要介紹了
yield return关键字怎么使用?
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在迭代器塊中用于向枚舉數對象提供值或發出迭代結束信號。它的形式為下列之一:
復制代碼
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.cs
using 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 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.cs
using 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 return关键字怎么使用?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ios逆向小试牛刀之操作手记
- 下一篇: named学习笔记