C# 2.0 的 迭代器 break的問題。

來源:互聯網
上載者:User
剛了C# 2.0 的迭代器感覺不錯,簡潔明了。
在迭代器塊中用於向枚舉數對象提供值或發出迭代結束訊號。它的形式為下列之一:
yield return expression;
yield break;

在下面的樣本中,迭代器塊(這裡是方法 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 break; 是在迭代器中發出迭代結束訊號用的。可是,如果是在迭代器的使用的時候外層break了,迭代器怎麼能得到“訊號”呢??能否??因為,迭代器如果被中斷,迭代器內部要作一些處理,比如:關閉個串連什麼的, 如下代碼所示:// yield-break-example.cs
using System;
using System.Collections;
public class List
{
    public static IEnumerable Power(int number, int exponent)
    {
        int counter = 0;
        connection.Open();
        int result = 1;
        while (counter++ < exponent)
        {
            result = result * number;
            yield return result;
        }
        connection.Close();
    }

    static void Main()
    {
        // Display powers of 2 up to the exponent 8:
        foreach (int i in Power(2, 8))
        {
            Console.Write("{0} ", i);
            if(i > 8) break;
        }
    }
}
 

我的connection怎麼才能正常Close呢???

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.