zoukankan      html  css  js  c++  java
  • GetEnumerator();yield

     GetEnumerator()方法的实质实现:

    说明:只要一个集合点出GetEnumerator方法,就获得了迭代器属性,就可以用MoveNextCurrent来实现foreach的效果,如上图。
     
     在.NET中,迭代器模式被IEnumeratorIEnumerable及其对应的泛型接口所封装。如果一个类实现了IEnumerable接口,那么就能够被迭代;调用GetEnumerator方法将返回IEnumerator接口的实现,它就是迭代器本身。
    所以一般能用foreach实现的,都可以让集合点出GetEnumerator( ),即得到迭代器,就可以用:
    while(ooo.MoveNext())
    {
    var  = ooo.Current;
    }//其实foreach后台实现机制如此!
    *****************************************************************************
    两个方法效果一样
     
    ********************************************************************************
    yield关键字用法:
    yield一般和迭代器,return或者break关键字结合使用一起使用。
    例如:
     1 publicclass List
     2 {
     3     public static IEnumerable Power(int number(2), int exponent(8))//使用yield return 使得返回值是一个迭代器类型
     4     {
     5         int counter =0;
     6         int result =1;
     7         while (counter++< exponent)
     8         {
     9             result = result * number;
    10             yield return result;
    11         }
    12     }
    13 
    14 staticvoid Main()
    15     {
    16         foreach (int i in Power(2, 8))
    17         {
    18             Console.Write("{0} ", i);
    19         }
    20     }
    21 }
    /*
    输出:
    Output: 2 4 8 16 32 64 128 256 // */

    了解枚举的机制后,就不得不讲道yield:

     1  class Program
     2  {
     3  staticvoid Main(string[] args)
     4      {
     5  foreach (var item in Person.Run())
     6          {
     7              Console.WriteLine(item);
     8          }
     9      }
    10 }
    11 class Person
    12 {
    13 public static IEnumerable<int> Run()
    14     {
    15          List<int> list = new List<int>();
    16 foreach (var item in list)
    17         {
    18 yieldreturn item;
    19         }
    20    }
    21  }

    //yield会给你生成一个枚举类,而这个枚举类和刚才List中的Enumerator枚举类又无比的一样

     
     
     
     
     
     

    yield关键字用法:
    yield一般和迭代器,return或者break关键字结合使用一起使用。
    例如:
    publicclass List
    {

        public static IEnumerable Power(int number(2), int exponent(8))//使用yield return 使得返回值是一个迭代器类型
        
    {
            int counter =0;
            int result =1;
            while (counter++< exponent)
            {
                result 
    = result * number;
                yield return result;
            }
        }

    staticvoid Main()
        {

            foreach (int i in Power(2, 8))
            {
                Console.Write(
    "{0} ", i);
            }
        }
    }
    /*
    Output:
    2 4 8 16 32 64 128 256       //
    */
  • 相关阅读:
    python日志设置[logging]
    python异常处理
    python可迭代对象、迭代器、生成器
    python字典操作
    python列表和元组的操作
    python字符串操作
    python深拷贝和浅拷贝
    python时间和日期的处理
    ssh
    SSH安全外壳协议
  • 原文地址:https://www.cnblogs.com/xiaoliangge/p/6006055.html
Copyright © 2011-2022 走看看