欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C#中yield用法使用說明

 更新時間:2015年10月13日 11:58:10   投稿:lijiao  
本文介紹了C#中yield的使用方法,yield 語句不能出現(xiàn)在匿名方法,其他相關(guān)內(nèi)容就仔細閱讀下文吧

在迭代器塊中用于向枚舉數(shù)對象提供值或發(fā)出迭代結(jié)束信號。它的形式為下列之一:
yield return <expression>;
yield break;
備注:
計算表達式并以枚舉數(shù)對象值的形式返回;expression 必須可以隱式轉(zhuǎn)換為迭代器的 yield 類型。
yield 語句只能出現(xiàn)在 iterator 塊中,該塊可用作方法、運算符或訪問器的體。這類方法、運算符或訪問器的體受以下約束的控制:不允許不安全塊。
方法、運算符或訪問器的參數(shù)不能是 ref 或 out。
yield 語句不能出現(xiàn)在匿名方法中。
當和 expression 一起使用時,yield return 語句不能出現(xiàn)在 catch 塊中或含有一個或多個 catch 子句的 try 塊中。
yield return 提供了迭代器一個比較重要的功能,即取到一個數(shù)據(jù)后馬上返回該數(shù)據(jù),不需要全部數(shù)據(jù)裝入數(shù)列完畢,這樣有效提高了遍歷效率。

以下是一個比較特殊的例子:

C# 中yield 的用法代碼引用:

using System;
using System.Collections;
using System.IO;
using Microsoft.Office.Interop.PowerPoint;
using Microsoft.Office.Core;
using System.Windows.Forms;
using System.Threading;

namespace test
{
  public class Persons : System.Collections.IEnumerable
  {
    #region IEnumerable 成員

    public System.Collections.IEnumerator GetEnumerator()
    {
      yield return "1";
      Thread.Sleep(5000);
      yield return "2";
      Thread.Sleep(5000);
      yield return "3";
      Thread.Sleep(5000);
      yield return "4";
      Thread.Sleep(5000);
      yield return "5";
      Thread.Sleep(5000);
      yield return "6";
    }

    #endregion
  }

  class program
  {
    static void Main()
    {
      Persons arrPersons = new Persons();
      foreach (string s in arrPersons)
      {
        System.Console.WriteLine(s);
      }

      System.Console.ReadLine();
    }
  }  
}

每隔5秒鐘, 控制臺就會輸出一個數(shù)據(jù),直到全部數(shù)據(jù)輸入完畢。

以上就是關(guān)于C#中yield用法使用說明,希望對大家的學習有所幫助。

相關(guān)文章

最新評論