• IEnumerable和IEnumerator


    IEnumerable接口和IEnumerator是两个比较重要的接口,当实现了该接口,就可以在Foreach中使用。下面来看看这两个东西。

    IEnumerable是一个声明式的接口,声明实现该接口的Class是Enumerable的,但并没有说明如何实现枚举器,IEnumerable的接口成员只有一个,那就是GetEnumerator方法,它返回对象的枚举数。

    public interface IEnumerable {
            IEnumerator GetEnumerator();
        }

    IEnumerator是一个实现式的接口,IEnumerator的接口包括三个成员函数:Current,MoveNext和Reset。

    public interface IEnumerator {
            object Current { get; }   //返回当前位置项的属性,因为是Object的类型引用,所以可以返回任何类型。
            bool MoveNext();      //把枚举的位置前进到下一项的,如果新位置有效则返回True,如果无效(比如到达了尾部),则返回False。
            void Reset();        //把位置重置到原始状态。
        }

    如果某类想实现Foreach,分别实现这两个接口,IEnumerable和IEnumerator通过IEnumerable的GetEnumerator()方法建立了连接。

    下面这个例子就实现了这两个接口,然后根据内容来Foreach,把内容显示出来~

    View Code
    class Program {
            static void Main(string[] args) {
                MyTestClass mt = new MyTestClass();
                foreach (var each in mt) {
                    Console.WriteLine(each);
                }
            }
        }
    
        class TestName : IEnumerator {
            String[] Name;
            int pos = -1;
            public TestName(string[] name) {
                Name = new string[name.Length];
                for (int i = 0; i < name.Length; i++) {
                    this.Name[i] = name[i];
                }
            }
    
            public object Current {        //Current
                get { return Name[pos]; }
            }
    
            public bool MoveNext() {    //MoveNext
                if (pos < Name.Length - 1) {
                    pos++;
                    return true;
                } else { return false; }
            }
    
            public void Reset() {    //Reset
                pos = -1;
            }
        }
    
        class MyTestClass : IEnumerable {
            string[] Name = { "AA", "BB", "CC", "DD" };
            public IEnumerator GetEnumerator() {
                return new TestName(Name);        //枚举数类的实例
            }
        }
  • 相关阅读:
    关于data初始化值
    switch的优化替代写法
    phpstorm安装xdebug
    如何将一个列表封装为一个树形结构
    Win10系统桌面图标距离间距变大的问题
    cnpm无法加载文件的问题
    0、springboot
    1、springboot2新建web项目
    Game游戏分析
    netty学习
  • 原文地址:https://www.cnblogs.com/socialdk/p/2932091.html
Copyright © 2020-2023  润新知