C#中的yield關鍵字的使用方法介紹

來源:互聯網
上載者:User

yield不能單獨放在try-catch塊中,如果try中有yield那麼,這個try塊後面不許跟著finally塊;也不能出現在匿名方法中,所以,看起來yield似乎並不常用,但是也不是不用。我前面有一個關於迭代器的例子《C#中的迭代器基礎》中就用到了。可以參考一下那個例子,但是這裡要再說的一點是我後來看到的,yield是跟return一起使用的,形式為yield return xxx,一般來說單獨的return在每個方法中只能存在一個。而yield則不同的是,可以出現連續多個。
迭代器,是一個連續的集合,出現多個yield return其實就是將這多個的yield return元素按照出現的順序儲存在迭代器的集合中而已。形如下面的形式: 複製代碼 代碼如下: public class CityCollection : IEnumerable<string>
{
string[] _Items = new string[] { "黑龍江", "吉林", "遼寧", "山東", "山西", "陝西", "河北", "河南", "湖南", "湖北", "四川", "廣西", "雲南", "其他" };
IEnumerator<string> IEnumerable<string>.GetEnumerator()
{
for (int i = 0; i < _Items.Length; i++)
{
yield return _Items[i];
yield return string.Format("Index:{0}", i);
}
}
IEnumerator IEnumerable.GetEnumerator()
{
for (int i = 0; i < _Items.Length; i++)
{
yield return _Items[i];
}
}
}

而返回的迭代結果就是這樣的:複製代碼 代碼如下: 黑龍江
Index:0
吉林
Index:1
遼寧
Index:2
山東
Index:3
山西
Index:4
陝西
Index:5
河北
Index:6
河南
Index:7
湖南
Index:8
湖北
Index:9
四川
Index:10
廣西
Index:11
雲南
Index:12
其他
Index:13

每一條yield return都是迭代器中的一個元素。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.