• foreach的拓展写自己的迭代器


    其实我们用的foreach之所以能有循环的结果本质通过Reflector最终在IL下看到,编译后的代码没有foreach的存在,foreach变成了这二个方法,“Current”,“Movenxet”。。。通过current和movenext实现循环。。。

    //自己的迭代器

    Person p = new Person();
    IEnumerator erto = p.GetEnumerator();
    while (erto.MoveNext())//因为MoveNext返回的是bool值当移到下一个还有值返回true
    {
    Console.WriteLine(erto.Current.ToString());//current拿到当前的值
    }
    Console.ReadKey();

    class Person:IEnumerable//并不是一定得实现IEnumerable接口,只要有GetEumerator这个方法就ok,一般可以通过实现IEumerable接口实现这个方法来获取方法名,就算干掉IEumerable接口照样能实现,一般情况大家都会实现IEumerable接口来写枚举器。
    {
    private string[] _name = { "hl", "aa", "cc", "bb", "ee" };

    public IEnumerator GetEnumerator()
    {
    return new GetPersonIndex(this._name);
    }
    }

    class GetPersonIndex:IEnumerator//自己写的枚举器通过实现这个IEnuerator实现接口的方法进行改写,这样就能通过foreach来实现循环
    {
    string[] arrStrs;

    public GetPersonIndex(string[] arr)
    {
    this.arrStrs = arr;
    }

    int index = -1;
    public object Current
    {
    get
    {
    while (index < arrStrs.Length && index>=0)
    {
    return this.arrStrs[index];
    }
    throw new IndexOutOfRangeException();
    }
    }

    public bool MoveNext()
    {
    if(index+1<arrStrs.Length)
    {
    index++;
    return true;
    }
    Reset();
    return false;
    }

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

  • 相关阅读:
    Python标准模块--logging
    Spark中决策树源码分析
    常见的相似或相异程度计算方法
    mpi4py实践
    集成学习
    决策树
    git使用
    Ubuntu 14.04 64bit 安装tensorflow(GPU版本)
    KNN算法
    一致性哈希算法原理及其在分布式系统中的应用
  • 原文地址:https://www.cnblogs.com/ffeng/p/3130190.html
Copyright © 2020-2023  润新知