Foreach原理

本质:实现了一个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遍历集合或数组的原理或实质。

分享面试题------

原文地址:https://www.cnblogs.com/yejiaojiao/p/5387686.html