首頁  >  文章  >  後端開發  >  C#中foreach與yield的實例詳解

C#中foreach與yield的實例詳解

黄舟
黄舟原創
2017-10-05 15:31:262003瀏覽

1. foreach

C#編譯器會把foreach語句轉換成IEnumerable介面的方法和屬性。


foreach (Person p in persons)
 {
     Console.WriteLine(p);
 }

foreach語句會解析為下面的程式碼片段。

呼叫GetEnumerator()方法,得到數組的一個枚舉

在while循環中,只要MoveNext()傳回true,就一直循環下去

#用Current屬性訪問陣列中的元素


IEnumerator enumerator = persons. GetEnumerator(); while (enumerator.MoveNext())
 {
    Person p = (Person) enumerator.Current;
    Console.WriteLine(p);
}

2. yield語句

yield語句的兩種形式:


#
yield return <expression>;yield break;

使用一個yield return語句傳回集合的一個元素

#包含yield語句的方法或屬性是迭代器。迭代器必須滿足以下要求

a. 傳回型別必須是IEnumerable、IEnumerable8742468051c85b06f0a0af9e3e506b5c、IEnumerator或 IEnumerator8742468051c85b06f0a0af9e3e506b5c。

b. 它不能有任何ref或out參數

yield return語句不能位於try-catch快。 yield return語句可以位於try-finally的try區塊


try
              {                  // ERROR: Cannot yield a value in the boday of a try block with a catch clause
                 yield return "test";
              }             catch
             { } 
              try
             {                 // 
                 yield return "test again";
             }             finally
             { } 
             try
             { }             finally
             { 
                 // ERROR: Cannot yield in the body of a finally clause
                yield return ""; 
             }

yield break語句可以位於try區塊或catch區塊,但是不能位於finally區塊

下面的例子是用yield return語句實作一個簡單集合的程式碼,以及用foreach語句迭代集合


using System;using System.Collections.Generic;namespace ConsoleApplication6
{    class Program
    {        static void Main(string[] args)
        {
            HelloCollection helloCollection = new HelloCollection();            foreach (string s in helloCollection)
            {
                Console.WriteLine(s);
                Console.ReadLine();
            }
        }
    }    public class HelloCollection
    {        
        public IEnumerator<String> GetEnumerator()
        {            // yield return语句返回集合的一个元素,并移动到下一个元素上;yield break可以停止迭代
            yield return "Hello";            yield return "World";
        }
    }
}

使用yield return語句實作以不同方式迭代集合的類別:


using System;using System.Collections.Generic;namespace ConsoleApplication8
{    class Program
    {        static void Main(string[] args)
        {
            MusicTitles titles = new MusicTitles();            foreach (string title in titles)
            {
                Console.WriteLine(title);
            }
            Console.WriteLine();            foreach (string title in titles.Reverse())
            {
                Console.WriteLine(title);
            }
            Console.WriteLine();            foreach (string title in titles.Subset(2, 2))
            {
                Console.WriteLine(title);
                Console.ReadLine();
            }
        }
    }    public class MusicTitles
    {        string[] names = { "a", "b", "c", "d" };        public IEnumerator<string> GetEnumerator()
        {            for (int i = 0; i < 4; i++)
            {                yield return names[i];
            }
        }        public IEnumerable<string> Reverse()
        {            for (int i = 3; i >= 0; i--)
            {                yield return names[i];
            }
        }        public IEnumerable<string> Subset(int index, int length)
        {            for (int i = index; i < index + length; i++)
            {                yield return names[i];
            }
        }
    }
}

#

以上是C#中foreach與yield的實例詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn