zoukankan      html  css  js  c++  java
  • 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;
    }
    }

  • 相关阅读:
    ural(Timus) 1346. Intervals of Monotonicity
    SGU 223 Little Kings
    poj 1243 One Person
    poj 1185 炮兵布阵
    poj 1191 棋盘分割
    poj 1187 陨石的秘密
    ACMICPC Live Archive 2451 Brackets Sequence
    将时间格式的字符串转换成日期类型浏览器兼容解决方案
    asp.net项目发布容易忽略的debug=true
    使用微软的Ajax控件遇到的后台js提示语句不起作用的解决方案其一
  • 原文地址:https://www.cnblogs.com/ffeng/p/3130190.html
Copyright © 2011-2022 走看看