zoukankan      html  css  js  c++  java
  • 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);        //枚举数类的实例
            }
        }
  • 相关阅读:
    Java获取一年里某季、某月、某周的第一天及最后一天时间的完整代码如下:
    django 将数组交给前台
    模板标签
    django 变量交给前台模板
    内核解密 | Oracle 18c 数据库安装ORA-12754的两种解决方案
    浅谈大型web系统架构
    浅谈大型web系统架构
    浅谈大型web系统架构
    浅谈大型web系统架构
    微信小程序把玩(三十二)Image API
  • 原文地址:https://www.cnblogs.com/socialdk/p/2932091.html
Copyright © 2011-2022 走看看