首页 > 学院 > 开发设计 > 正文

IEnumerable 接口 实现foreach 遍历 实例

2019-11-17 03:14:39
字体:
来源:转载
供稿:网友

IEnumerable 接口 实现foreach 遍历 实例

额 为啥写着东西?

有次面试去,因为用到的时候特别少 所以没记住, 这个单词 怎么写!

经典的面试题:

能用foreach遍历访问的对象的要求?

答: 该类实现IEnumetable 接口 声明 GetEnumerator 方法。

这是统一的答案 非常正直 不是嘛?

但是 你真正的写过 这个功能吗?

今天看MSDN 关于IEnumetable 第一次看这个接口 没看明白 ! 怎么办? 自己跟着写一次! 这个办法非常好,我特推荐!

命名规则就随便了, 别喷。

/// <summary>   /// 首先继承Ienumerable 接口   /// </summary>   public class Ns : IEnumerable    {        PRivate List<object> list = new List<object>(); // 先定义委会的集合对象        private string name;        private string age;        private int id;        public string Name        {            get            {                return this.name;            }            set            {                this.list.Add(value);   // 特殊操作  赋值的时候将其先添加到维护的集合对象中                this.name = value;            }        }        public string Age        {            get            {                                return this.age;            }            set            {                this.list.Add(value);   // 特殊操作  赋值的时候将其先添加到维护的集合对象中                this.age = value;            }        }        public int Id        {            get            {                                return this.id;            }            set            {                this.list.Add(value);  // 特殊操作  赋值的时候将其先添加到维护的集合对象中                this.id = value;            }        }       /// <summary>       ///  必须实现 GetEnumerator方法 更具返回类型 IEnumerator 来创建一个继承 IEnumerator接口的内部类       /// </summary>       /// <returns></returns>        public IEnumerator GetEnumerator()        {            return new NsIEnumerator(this);        }        /// <summary>        /// IEnumerator接口的内部类  PS  该类其实就是对 维护着的集合对象做遍历操作的        /// </summary>        class NsIEnumerator : IEnumerator        {            private int ids = -1;   // 当前下标            private Ns n;           // 传递过来的 需要遍历的类            public NsIEnumerator(Ns N)            {                this.n = N;            }            public bool MoveNext()     // 判断是否遍历完毕            {                this.ids++;                return (this.ids < this.n.list.Count);            }            public void Reset()     // 将下标重置            {                this.ids = -1;            }            public object Current   //  这个就是通过变换的下标获取到的对应的 数据            {                get                {                    return this.n.list[this.ids];                }            }        }        static void Main(string[] args)        {            Ns n = new Ns();            n.Id = 1;            n.Name = "liwen";            n.Age = "18";                       foreach (var n1 in n)            {                Console.WriteLine(n1);            }            Console.ReadKey();        }    }

没啥特别的 ,就是觉得可能很多人也和我一样知道这个功能 但是却自己没实现过。 贴上个来让那些人看一下。方便大家嘛


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表