IL角度理解for 與foreach的區別——迭代器模式
目錄- IL角度理解for 與foreach的區別——迭代器模式
- 1 最常用的設計模式
- 1.1 背景
- 1.2 摘要
- 2 遍歷元素
- 3 洗掉元素
- 3.1 for洗掉例子
- 3.2 foreach洗掉例子
- 4 修改元素
- 4.1 for修改
- 4.2 foreach修改
- 5 修改元素屬性
- 6 什么場景下用foreach
- 7 小結
- 1 最常用的設計模式
1 最常用的設計模式
1.1 背景
如果問你最常用的設計模式是哪種?你可能會說單例模式,工廠模式,但根據我在專案里的經驗,一個完整的應用,應該是迭代器模式,
1.2 摘要
- 本文不講怎么去實作迭代器模式,但介紹迭代器模式到底是什么?為什么迭代器回圈迭代時,無法洗掉元素,無法修改元素;
- 本文講的迭代器,媒介主要是C#語言下的foreach,微軟爸爸已經在C#的foreach中幫我們實作了迭代器代碼,關于迭代器,我們只需要知道他是什么,他的特性是什么,為什么要用他?
- 迭代器有什么優點,有什么缺點?
- 在本文中迭代器模式約等于foreach
2 遍歷元素
在本項中將會帶大家一起進入迭代器模式下的IL代碼,看看迭代器內部是怎么去進行回圈迭代的;
如下代碼實作了for回圈列印集合中的所有元素,以及foreach迭代列印集合中的所有元素,
static void Main(string[] args)
{
List<int> intList = new List<int>();
intList.Add(1);
intList.Add(2);
for(var i=0;i<intList.Count;i++)
{
Console.WriteLine("元素for遍歷列印:" + intList[i]);
}
foreach (var item in intList)
{
Console.WriteLine("元素foreach遍歷列印:" + item);
}
}
代碼輸出:

可以看到兩種列印方式效果一致;for回圈任一一種語言都有,大家再熟悉不過,這里不再贅述,我們來看下foreach迭代器模式的IL代碼(如果當前網頁太小,看不清,請將圖片右鍵另存打開,或者將圖片拖到瀏覽器新視窗打開);

大概思路如下:List 下有個迭代器Enumerator,可以通過List下的GetEnumerator方法獲得此迭代器集合;然后通過迭代器的get_Current方法來獲取當前第一個元素,迭代器的MoveNext()方法判斷下一元素是否存在,如果存在取出回圈;不存在結束迭代回圈模式;最終,將迭代程序中產生的系統非托管資源釋放;
迭代器代碼如下:
var enumerator = intList.GetEnumerator();
while (enumerator.MoveNext())
{
Console.WriteLine("迭代器模式遍歷列印:" + enumerator.Current);
}
Console.ReadLine();
3 洗掉元素
3.1 for洗掉例子
List<int> intList = new List<int>();
intList.Add(1);
intList.Add(2);
for(var i=0;i<intList.Count;i++)
{
if (intList[i] == 1)
{ intList.Remove(1); }
}
Console.WriteLine("集合中元素數量:" + intList.Count);
Console輸出
集合中元素數量:1
這說明for洗掉成功
3.2 foreach洗掉例子
foreach (var item in intList)
{
if (item==1)
{ intList.Remove(1); }
}
Console.WriteLine("集合中元素數量:" + intList.Count);

從如上拋出的例外得得知 var enumerator = intList.GetEnumerator();迭代器在回圈迭代中是不允許對該迭代器進行洗掉操作的,如果需要洗掉操作,可以再這個集合基礎上做linq操作;因為迭代器在回圈迭代中是一個值物件的存在,不允許變更迭代器物件的內容;
思考
如下代碼也是運用了迭代器模式,為什么能洗掉集合元素了?讀者自行思考哈,這也是迭代器方式下犧牲記憶體來洗掉/修改元素的一種方法,
foreach (var item in dictionary.ToList()) {
Debug.Log(item.Key + "," + item.Value);
if (item.Key.Equals("s11")) {
dictionary.Remove(item.Key);
}
}
4 修改元素
4.1 for修改
List<int> intList = new List<int>();
intList.Add(1);
intList.Add(2);
for(var i=0;i<intList.Count;i++)
{
if (intList[i] == 1)
{ intList[i]=3; }
Console.WriteLine("集合中元素遍歷:" + intList[i]);
}
輸出:
集合中元素遍歷:3
集合中元素遍歷:2
從如上輸出看出,for修改成功
4.2 foreach修改
直接編譯就通不過

5 修改元素屬性
如下程式,會去修改迭代器元素的屬性,并且在for跟foreach下都能運行成功,
class Program
{
static void Main(string[] args)
{
List<protocol> protocols = new List<protocol>();
var p1 = new protocol();
p1.bytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
var p2 = new protocol();
p2.bytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
protocols.Add(p1);
protocols.Add(p2);
foreach (var item in protocols)
{
item.bytes = p2.bytes;
item.intList.Add(1);
}
for (var i=0;i<protocols.Count;i++)
{
protocols[i].bytes = p1.bytes;
protocols[i].intList.Add(1);
protocols[i] = p1;
}
Console.WriteLine("程式運行成功");
Console.ReadLine();
}
}
public class protocol
{
public byte[] bytes= { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
public List<int> intList=new List<int>();
}
6 什么場景下用foreach
既然,for效率更高,foreach效率不及for,for能做的事foreach不能做(修改洗掉元素),是不是沒有foreach的用武之地了呢,大錯特錯了,恰恰相反,每個專案里用的最多的反而是foreach迭代器模式,我統計了下超過工廠模式跟單例模式,不信你自己去數foreach的數量,但是在遍歷散列集合時,如字典,for就會失效了,因為下標不是有序數值了,而是看上去無序的內部散列演算法,這時foreach遍歷字典就很有用,他定義了一個列舉器(迭代器),而這個列舉器統一了,getCurrent(), moveNext()等用于迭代的方法;
foreach (var item in dictionary.ToList()) {
Debug.Log(item.Key + "," + item.Value);
if (item.Key.Equals("s11")) {
dictionary.Remove(item.Key);
}
}
像上面的用for,for回圈的i與字典的key(自定義,一般是string型別)是沒辦法建立映射關系的;所以無法用for回圈
7 小結
- for與foreach都可以遍歷陣列/集合,不過for則在較復雜的回圈中效率更高;
- foreach不可以洗掉/修改集合元素,而for可以;
- foreach和for都可以修改元素里面的屬性;
- foreach適合遍歷用了哈希演算法的散列,集合,字典;
著作權宣告:本文為博主原創文章,遵循 CC 4.0 BY-SA 著作權協議,轉載請附上原文出處鏈接和本宣告, 本文鏈接:https://www.cnblogs.com/JerryMouseLi/p/13977500.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/217964.html
標籤:其他
