C# foreach 的实现 和探索

除了foreach 另外一种方式遍历

  private static void TestForeach1()
        {
            List<int> ls = new List<int>();
            for (int i = 0; i < 10; i++)
            {
                ls.Add(i);
            }
            //进行遍历
            Console.WriteLine("常规遍历");
            foreach (var item in ls)
            {
                Console.WriteLine(item);
            }
            Console.WriteLine("另一种遍历方式");
            IEnumerator<int> numberIntEnumerator = ls.GetEnumerator();
            while (numberIntEnumerator.MoveNext())
            {
                var currentInt = numberIntEnumerator.Current;
                Console.WriteLine(currentInt);
            }
           
        }

从上面的例子中我们能够看到 foreach 一些本质, 它包含了一个 Enumerator 类
怎么让自己类 实现能被foreach 遍历呢?
model 实体

   public class PeopleLoping
    {
        public string Name { get; set; }
        public string Address { get; set; }
    }

集合要实现 IEnumerable 接口 这个是基本。
两种方式实现 Enumerator 方式,一种是自己实现,另外一种使用语法糖 来让编译器帮你生成

 public class PeopleSet : IEnumerable
    {
        private List<PeopleLoping> enumerableLs = new List<PeopleLoping>();


        #region 
        public IEnumerator GetEnumerator()
        {
            for (int i = 0; i < enumerableLs.Count; i++)
            {
                // 编译器帮你生成 Enumerator 类
                yield return enumerableLs[i];
            }
            
        }
        #endregion

        // 自己实现  Enumerator  类方法

        //public IEnumerator GetEnumerator()
        //{
        //    return new PeopleEnumerator(enumerableLs);
        //}



        public void Add(PeopleLoping p)
        {
            this.enumerableLs.Add(p);
        }

        //弄成内部类  免得污染类空间
         class PeopleEnumerator : IEnumerator
        {
            public List<PeopleLoping> Peoples = new List<PeopleLoping>();
            private int idx = -1;

            public PeopleEnumerator(List<PeopleLoping> PeopleLs)
            {
                this.Peoples = PeopleLs;
            }

            public bool MoveNext()
            {
                idx++;
                return Peoples.Count > idx;

            }

            public void Reset()
            {
                idx = -1;
            }

            public object Current => Peoples[idx];
        }
    }

以上即是,自己的理解 C# 提供的迭代器模式。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

望天hous

你的鼓励是我最大动力~谢谢啦!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值