C#中的yield關(guān)鍵字的使用方法介紹
更新時(shí)間:2013年04月27日 10:59:40 作者:
yield這個(gè)關(guān)鍵字是和迭代器掛鉤的,而且是與return一起以yield return的形式合用的,用來(lái)返回迭代器中的條目。
yield不能單獨(dú)放在try-catch塊中,如果try中有yield那么,這個(gè)try塊后面不許跟著finally塊;也不能出現(xiàn)在匿名方法中,所以,看起來(lái)yield似乎并不常用,但是也不是不用。我前面有一個(gè)關(guān)于迭代器的例子《C#中的迭代器基礎(chǔ)》中就用到了。可以參考一下那個(gè)例子,但是這里要再說(shuō)的一點(diǎn)是我后來(lái)看到的,yield是跟return一起使用的,形式為yield return xxx,一般來(lái)說(shuō)單獨(dú)的return在每個(gè)方法中只能存在一個(gè)。而yield則不同的是,可以出現(xiàn)連續(xù)多個(gè)。
迭代器,是一個(gè)連續(xù)的集合,出現(xiàn)多個(gè)yield return其實(shí)就是將這多個(gè)的yield return元素按照出現(xiàn)的順序存儲(chǔ)在迭代器的集合中而已。形如下面的形式:
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];
}
}
}
而返回的迭代結(jié)果就是這樣的:
黑龍江
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都是迭代器中的一個(gè)元素。
迭代器,是一個(gè)連續(xù)的集合,出現(xiàn)多個(gè)yield return其實(shí)就是將這多個(gè)的yield return元素按照出現(xiàn)的順序存儲(chǔ)在迭代器的集合中而已。形如下面的形式:
復(fù)制代碼 代碼如下:
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];
}
}
}
而返回的迭代結(jié)果就是這樣的:
復(fù)制代碼 代碼如下:
黑龍江
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都是迭代器中的一個(gè)元素。
相關(guān)文章
深入DropDownList用法的一些學(xué)習(xí)總結(jié)分析
本篇文章是對(duì)DropDownList的用法進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-06-06C#中的三種定時(shí)計(jì)時(shí)器Timer用法介紹
這篇文章介紹了C#中的三種定時(shí)計(jì)時(shí)器Timer的用法,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-03-03基于C#實(shí)現(xiàn)端口掃描器(單線程和多線程)
本文主要介紹了基于C#分別通過(guò)單線程和多線程實(shí)現(xiàn)端口掃描,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-12-12利用C#實(shí)現(xiàn)網(wǎng)絡(luò)爬蟲(chóng)
這篇文章主要介紹了利用C#實(shí)現(xiàn)網(wǎng)絡(luò)爬蟲(chóng),完整的介紹了C#實(shí)現(xiàn)網(wǎng)絡(luò)爬蟲(chóng)詳細(xì)過(guò)程,感興趣的小伙伴們可以參考一下2016-03-03