【C#】IEnumerable接口/IEnumerator接口
https://blog.csdn.net/CodeRookieGuo/article/details/77507636
https://blog.csdn.net/CodeRookieGuo/article/details/86163049
foreach语句作为从C#1时代就已经存在的语法。foreach是如何对集合进行迭代访问的呢?很显然,集合并不是天生就支持遍历(迭代)的,而是继承了IEnumerable接口并实现了该接口所包含的唯一一个方法GetEnumerator()。换句话说,凡是实现了IEnumerable接口的类型,都是可以被迭代访问的。foreach语句实现遍历的功能实际上就是通过调用集合的GetEnumerator()方法来实现的。
public interface IEnumerable{ IEnumerator GetEnumerator(){} }
public interface IEnumerator{ bool MoveNext(); object Current(); void Reset(); }
继承IEnumerable接口并实现GetEnumerator()的集合类才可以通过foreach遍历。通过linq过滤得到的数据可以给IEnumerable实例变量。
GetEnumerator()返回迭代器,类型是实现了IEnumerator接口的类。迭代器有Current属性,MoveNext()、Reset()。
代码里的internal权限修饰符:https://blog.csdn.net/qq_30725967/article/details/127124636
成员称为内部类型或成员,只是它所修饰的类只能在同一个程序集中被访问,而同一个程序集表示同一个dll程序集或同一个exe程序集。在vs中一个项目会生成一个dll文件,因此这个dll或这个项目也就是一个程序集。
static void Main(string[] args) { Person[] p1 = new Person[]{ new Person(10,"wang"), new Person(20,"zang"), new Person(30,"lang"), }; foreach(var ii in p1){ Console.WriteLine($"age={ii.Age},name={ii.Name}"); } } public static async Task CalculateSum(int a, int b) { int c = 0; await Task.Run(() => { Console.WriteLine(Thread.CurrentThread.ManagedThreadId + ":start"); Thread.Sleep(1000 * 3); Console.WriteLine(Thread.CurrentThread.ManagedThreadId + ":end"); c = a + b; }); Console.WriteLine(c); } public class Person{ private int _age; private string _name; public Person(int a, string n){ this._age=a; this._name=n; } public int Age{ set{ this._age=value; } get{ return this._age; } } public string Name{ set{ this._name=value; } get{ return this._name; } } } public class People:IEnumerable{ private Person[] people; public People(Person[] pp){ this.people=pp; } public Person this[int idx]{ get=>people[idx]; } public int Count{ get => this.people.Length; } //注意:GetEnumerator IEnumerator IEnumerable.GetEnumerator(){ return new peopleIterator(this); } } public class peopleIterator:IEnumerator{ private People pp; private int index; public peopleIterator(People pp){ this.pp=pp; index=-1; } object IEnumerator.Current{ get => pp[index]; } bool IEnumerator.MoveNext(){ return (++this.index) < this.pp.Count; } void IEnumerator.Reset(){ this.index=-1; } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了