Foreach原理

本质:实现了一个IEnumerable接口,面试

01.为何数组和集合能够使用foreach遍历?数组

解析:由于数组和集合都实现了IEnumerable接口,该接口中只有一个方法,GetEnumerator()数据结构

02.数组是一种数据结构,它包含若干相同类型的变量。数组是使用类型声明的:type[] arrayName;this

03.数组类型是从抽象基类型 Array 派生的引用类型。因为此类型实现了 IEnumerable ,所以能够对 C# 中的全部数组使用 foreach 迭代。(摘自MSDN)spa

咱们都知道foreach能够遍历ArrayList集合code

咱们能够F12过去看看它的内部微软写好的代码blog

01.索引

.接口

 

02.get

 

 

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遍历集合或数组的原理或实质。

 

分享面试题------

相关文章
相关标签/搜索