欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C#中的IEnumerable簡介及簡單實(shí)現(xiàn)實(shí)例

 更新時(shí)間:2015年03月16日 09:47:34   投稿:junjie  
這篇文章主要介紹了C#中的IEnumerable簡介及簡單實(shí)現(xiàn)實(shí)例,本文講解了IEnumerable一些知識并給出了一個(gè)簡單的實(shí)現(xiàn),需要的朋友可以參考下

IEnumerable這個(gè)接口在MSDN上是這么說的,它是一個(gè)公開枚舉數(shù),該枚舉數(shù)支持在非泛型集合上進(jìn)行簡單的迭代。換句話說,對于所有數(shù)組的遍歷,都來自IEnumerable,那么我們就可以利用這個(gè)特性,來定義一個(gè)能夠遍歷字符串的通用方法.

下面先貼出code.

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就是迭代器的實(shí)現(xiàn),position字段存儲當(dāng)前的迭代位置,通過Current屬性可以得到當(dāng)前迭代位置的元素,MoveNext方法用于更新迭代位置,并且查看下一個(gè)迭代位置是不是有效的。

當(dāng)我們通過VS單步調(diào)試下面語句的時(shí)候:

復(fù)制代碼 代碼如下:

foreach (var c in charList)

代碼首先執(zhí)行到foreach語句的charList處獲得迭代器CharIterator的實(shí)例,然后代碼執(zhí)行到in會調(diào)用迭代器的MoveNext方法,最后變量c會得到迭代器Current屬性的值;前面的步驟結(jié)束后,會開始一輪新的循環(huán),調(diào)用MoveNext方法,獲取Current屬性的值。

通過C# 1.0中迭代器的代碼看到,要實(shí)現(xiàn)一個(gè)迭代器就要實(shí)現(xiàn)IEnumerator接口,然后實(shí)現(xiàn)IEnumerator接口中的MoveNext、Reset方法和Current屬性。

在C# 2.0中可以直接使用yield語句來簡化迭代器的實(shí)現(xiàn)。

如上面public IEnumerator GetEnumerator()方法中注釋掉的部分。
通過上面的代碼可以看到,通過使用yield return語句,我們可以替換掉整個(gè)CharIterator類。

yield return語句就是告訴編譯器,要實(shí)現(xiàn)一個(gè)迭代器塊。如果GetEnumerator方法的返回類型是非泛型接口,那么迭代器塊的生成類型(yield type)是object,否則就是泛型接口的類型參數(shù)。

相關(guān)文章

最新評論