• IEnumerator与IEnumerable探讨


    一套完整的 IEnumerator 和IEnumerable 关系

        public class MyClass : IEnumerator
    {
    public MyClass(int Size)
    {
    this.Index = -1;
    Info = new string[Size];
    for (int i = 0; i < Size; i++)
    {
    Info[i] = i.ToString();
    }
    }

    private string[] Info;
    public int Index;
    public object Current { get { return Info[Index]; } }

    public bool MoveNext()
    {
    Index++;
    return Index >= Info.Length ? false : true;
    }

    public void Reset()
    {
    Index = -1;
    }

    }
    public class MyClassCollection : IEnumerable
    {
    private MyClass ml = null;
    public MyClassCollection(int Size)
    {
    ml = new MyClass(Size);
    }
    public IEnumerator GetEnumerator()
    {
    return (IEnumerator)ml;
    }
    }

    调用:

     MyClassCollection cl = new MyClassCollection(10);
                foreach (var item in cl)
                {
                    Console.WriteLine(item);
                }

    结果:0到9

    个人理解:1.IEnumerable 只是用来被 循环调用。不能自己实现foreach,需要用GetEnumerator 将自己的成员。传给IEnumerator,进行循环。

    也就是 在foreach中 item 其实是 IEnumerator 中的返回的结果。

    2.必须知道的事  IEnumerable 必须实现  接口中 GetEnumerator方法。

    IEnumerator 实现  Current。MoveNext。Reset (不然会空引用)

    3.可以将IEnumerator和 IEnumerable 结合到一块。

    4. 可以不继承IEnumerable,但一定要实现 GetEnumerator方法。~!!!!!

    待续。。

  • 相关阅读:
    c# 委托
    datagrid加下拉列表dropdownlist
    MySQL存储过程的基本函数(三)
    MySQL存储过程详解 mysql 存储过程(二)
    MySQL存储过程(一)
    SFTP 文件上传下载引用代码
    JAVA SFTP文件上传、下载及批量下载
    java中遍历MAP的几种方法
    POSTGRESQL 导入导出
    db2move 数据导出整理
  • 原文地址:https://www.cnblogs.com/shikyoh/p/2246456.html
Copyright © 2020-2023  润新知