c# foreach学习

c#的foreach需要类去实现 IEnumerable接口 还有个泛型的IEnumerable<T> 接口

 

我们从List的源码里可以看到 

 就是转了一层 所以我们直接从原始的IEnumerable接口实现就好

复制代码
 public class ATest : IEnumerable
 {
     public int Num { get; set; }
     private ATest[] per;
     public ATest(int num)
     {
         Num = num;
     }

     public ATest(ATest[] arr)
     {
         per= arr;
     }
     public IEnumerator GetEnumerator()
     {
         Console.WriteLine("new ATestEnumerator");
         return new ATestEnumerator(per);
     }
 }
复制代码

代码如上面所示,最主要的是这个GetEnumerator()方法,我们可以看到它需要我们返回IEnumerator类型的类

 注意2个接口的名称不要搞混了

 

复制代码
    public class ATestEnumerator : IEnumerator
    {
        public object Current
        {
            get
            {
                    return _ATests[postition];
            }
        }
        int postition = -1;
        public ATest[] _ATests;

        public ATestEnumerator(ATest[] aTests)
        {
            _ATests = aTests;
        }

        public bool MoveNext()
        {
            return ++postition < _ATests.Length;
        }

        public void Reset()
        {
            postition = -1;
        }
    }
复制代码

代码如上面所示

foreach的执行逻辑是:

  1. 先执行GetEnumerator()获取IEnumerator
  2. 然后执行MoveNext()判断是否还有下一个数据
  3. 最后拿到Current的对象
posted @   大大只植物  阅读(12)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示