C#: IEnumerable

39 篇文章 2 订阅

IEnumerable这个接口在MSDN上是这么说的,它是一个公开枚举数,该枚举数支持在非泛型集合上进行简单的迭代。换句话说,对于所有数组的遍历,都来自IEnumerable,那么我们就可以利用这个特性,来定义一个能够遍历字符串的通用方法.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
  
namespace mycs
{
  class Program
  {
    static void Main(string[] args)
    {
      charlist mycharlist = new charlist("hello world");
      foreach (var c in mycharlist)
      {
        Console.Write(c);
      }
     Console.ReadLine();
    }
  }
  
  class charlist : IEnumerable
  {
    public string TargetStr { get; set; }
  
    public charlist(string str)
    {
      this.TargetStr = str;
    }
    public IEnumerator GetEnumerator()
    {
      //c# 1.0
      return new CharIterator(this.TargetStr);
      //c# 2.0
      /*
      for (int index = this.TargetStr.Length; index > 0;index-- )
      {
        yield return this.TargetStr[index - 1];
      }
       */
    }
  }
  class CharIterator : IEnumerator
  {
    public string TargetStr { get; set; }
    public int position { get; set; }
  
    public CharIterator(string targetStr)
    {
      this.TargetStr = targetStr;
      this.position = this.TargetStr.Length;
    }
    public object Current
    {
      get
      {
        if (this.position==-1||this.position==this.TargetStr.Length)
        {
          throw new InvalidOperationException();
        }
        return this.TargetStr[this.position];
      }
    }
    public bool MoveNext()
    {
      if (this.position!=-1)
      {
        this.position--;
      }
      return this.position > -1;
    }
    public void Reset()
    {
      this.position = this.TargetStr.Length;
    }
  }
}

在上面的例子c# 1.0中,CharIterator就是迭代器的实现,position字段存储当前的迭代位置,通过Current属性可以得到当前迭代位置的元素,MoveNext方法用于更新迭代位置,并且查看下一个迭代位置是不是有效的。

当我们通过VS单步调试下面语句的时候:

代码如下:

foreach (var c in charList)
代码首先执行到foreach语句的charList处获得迭代器CharIterator的实例,然后代码执行到in会调用迭代器的MoveNext方法,最后变量c会得到迭代器Current属性的值;前面的步骤结束后,会开始一轮新的循环,调用MoveNext方法,获取Current属性的值。

通过C# 1.0中迭代器的代码看到,要实现一个迭代器就要实现IEnumerator接口,然后实现IEnumerator接口中的MoveNext、Reset方法和Current属性。

在C# 2.0中可以直接使用yield语句来简化迭代器的实现。

如上面public IEnumerator GetEnumerator()方法中注释掉的部分。
通过上面的代码可以看到,通过使用yield return语句,我们可以替换掉整个CharIterator类。

yield return语句就是告诉编译器,要实现一个迭代器块。如果GetEnumerator方法的返回类型是非泛型接口,那么迭代器块的生成类型(yield type)是object,否则就是泛型接口的类型参数。


运行结果:dlrow olleh

如果在public IEnumerator GetEnumerator()中c#2.0中改

 for (int index = 0;index < this.TargetStr.Length; index++ )
                {
                  yield return this.TargetStr[index];
                }
运行结果:hello world

 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值