本質:實現了一個IEnumerable接口,
01.為什麼數組和集合可以使用foreach遍歷?
解析:因為數組和集合都實現了IEnumerable接口,該接口中只有一個方法,GetEnumerator()
02.數組是一種數據結構,它包含若干相同類型的變量。數組是使用類型聲明的:type[] arrayName;
03.數組類型是從抽象基類型 Array 派生的引用類型。由於此類型實現了 IEnumerable ,因此可以對 C# 中的所有數組使用 foreach 迭代。(摘自MSDN)
我們都知道foreach可以遍歷ArrayList集合
我們可以F12過去看看它的內部微軟寫好的代碼
01.
.
02.

03.

04.

下面我們自己來模擬實現微軟的方法:
1.MyCollection類實現IEnumerable接口
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Foreach原理
{
//自定義類型:實現IEnumerable接口,證明這個類型保存的數據能被foreach遍歷
public class MyCollection : IEnumerable
{
//01給集合添值得方法
public void Add(object o)
{
list.Add(o);
}
//02定義一個集合
ArrayList list = new ArrayList();
//03實現GetEnumerator方法
public IEnumerator GetEnumerator()
{
return new MyIEnumerator(list);
}
}
}
02.MyIEnumerator類實現IEnumerator接口
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Foreach原理
{
//IEnumerator:支持對非泛型集合的簡單迭代
public class MyIEnumerator : IEnumerator
{
//定義一個List集合
ArrayList list = new ArrayList();
public MyIEnumerator(ArrayList mylist)
{
//給當前類的集合賦值
list = mylist;
}
//默認將集合的索引指向前一個 即第一條數據之前
private int i = -1;
//返回當前循環遍歷索引的值
public object Current
{
get { return list[i]; }
}
//實現接口的Movenext方法
public bool MoveNext()
{
bool flag = false;//默認為沒有數據
if (i < list.Count - 1)
{
//證明集合中有數據讓索引加1
i++;
//改變bool值為true
flag = true;
}
return flag;
}
//把i初始化為-1
public void Reset()
{
i = -1;
}
}
}
03.在Main方法中調用
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Foreach原理
{
class Program
{
static void Main(string[] args)
{
//01.實例化實現了IEnumerable接口的MyCollection類
MyCollection list = new MyCollection();
//02.向集合添加元素
list.Add("小張");
list.Add("小王");
//03.方可使用foreach循環遍歷出結果
foreach (string item in list)
{
Console.WriteLine(item);
}
Console.ReadKey();
}
}
}
這就是foreach遍歷集合或數組的原理或實質。