zoukankan      html  css  js  c++  java
  • C#中yield return的思想

    C#中为什么引入yield return? 我想是为了使for each更容易使用.yield return的思想也就是foreach的思想:为了使遍历的语义更加自然,接近人类思想。

    C#编译器在背后为我们作了大量的工作,以便我们代码的可读性更好!请看下面代码:

    using System;
    using System.Text;
    using System.Collections;

    namespace yieldReturn
    {
        
    public class List
        {
            
    //using System.Collections;
            public static IEnumerable Power(int number, int exponent)
            {
                
    int counter = 0;
                
    int result = 1;
                
    while (counter++ < exponent)
                {
                    result 
    = result * number;
                    
    yield return result;
                }
            }

            
    static void Main()
            {
                 
    //Display powers of 2 up to the exponent 8:
                foreach (int i in Power(28))
                {
                    Console.Write(
    "{0} ", i);
                }
                Console.Read();
            }
        }

    }

    有了yield return,可以方便地为我们提供foreach下一个要访问的元素!

  • 相关阅读:
    hisi3516/3519开发(二)—xshell连接串口
    linux svn使用
    IdentityServer4 源码介绍
    想写博客
    # VS2019 快捷键插入当前时间
    # 使用 vscode markdown 遇到的问题
    # 学Vue
    teXt使用
    Linux基础
    NopCommerce(Core)学习目录
  • 原文地址:https://www.cnblogs.com/hjblog/p/2153091.html
Copyright © 2011-2022 走看看