c#-foreach的秘密

 

foreach的秘密

class Program

    {

        static void Main(string[] args)

        {

            //创建Person的对象

            Person p1=new Person();

 

            //遍历p1因为实现了IEnumerable接口

            foreach (var item in p1)

            {

                Console.WriteLine(item);

            }

            

            Console.ReadKey();

        }

    }

 

    //实现了Ienumerable接口就可以遍历对象了

    //实现IIndextor因为EnumeratorIndex是泛型类需要实现IIndextor接口

    public class Person:IEnumerable,IIndextor

    {

        public string[] strs = new string[6];

        

        public string this[int Index]

        {

            get { return strs[Index]; }

            set { strs[Index] = value; }

        }

 

        public Person()

        {

            strs[0] = "3sfgew";

            strs[1] = "322";

            strs[2] = "34";

            strs[3] = "3434";

            strs[4] = "3ww";

            strs[5] = "3sdfe";

        }

 

        public IEnumerator GetEnumerator()

        {

            //返回Ienumerator的实现类

            return new EnumeratorIndex<Person>(this);

        }

 

        public int IndexLength

        {

            get { return strs.Length; }

        }

    }

 

    //定义索引器的接口

    public interface IIndextor

    {

        string this[int Index] { get; }

        int IndexLength { get; }

    }

 

    public class EnumeratorIndex<T> : IEnumerator where T:IIndextor

    {

        T p1;

 

        int Index;

 

        //构造函数

        public EnumeratorIndex(T p1)

        {

            //给必须的对象赋值

            //Index的初始值必须是-1

            Index = -1;

            this.p1 = p1;

        }

 

        //返回当前的对象

        public object Current

        {

            get { return p1[Index]; }

        }

 

        //使索引前进到下一个

        public bool MoveNext()

        {

            if (Index < p1.IndexLength - 1)

            {

                Index++;

                return true;

            }

            else

            {

                return false;

            }

        }

 

        //初始化索引

        public void Reset()

        {

            Index = -1;

        }

    }

 

 

posted on   李鹏周  阅读(221)  评论(0编辑  收藏  举报

编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 2025年我用 Compose 写了一个 Todo App
· 张高兴的大模型开发实战:(一)使用 Selenium 进行网页爬虫
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示