zoukankan      html  css  js  c++  java
  • 探秘C#中的yield关键字

    在"C#中,什么时候用yield return"中,我们了解到:使用yield return返回集合,不是一次性加载到内存中,而是客户端每调用一次就返回一个集合元素,是一种"按需供给"。本篇来重温yield return的用法,探秘yield背后的故事并自定义一个能达到yield return相同效果的类,最后体验yield break的用法。

    class Program
    {
      static Random r = new Random();
      static IEnumerable<int> GetList(int count)
      {
        List<int> list = new List<int>();
        for (int i = 0; i < count; i++)
        {
          list.Add(r.Next(10));
        }
        return list;
    }

    static IEnumerable<int> GetList2(int count)
    {
      for (int i = 0; i < count; i++)
      {
        yield return r.Next(10);
      }
    }
    static void Main(string[] args)
    {

      foreach (int item in GetList2(5))
      Console.WriteLine(item);

      Console.WriteLine("Hello World!");
    }

    void test()
    {
      Func<string, int> del3 = (string text) => text.Length;

      // 可以省略参数类型string,把上面代码再简化为:
      Func<string, int> del4 = (text) => text.Length;

      int M = del3("FFFFFJJJJJ");

      int n = del4("2222");
    }


    }

  • 相关阅读:
    20150128-堆雪人
    20150127-梦里笑醒的声音
    20150126-渡口
    20150125-阴天
    FastAdmin 的上传代码在哪里?
    在 Linux 安装 IIS?
    FastAdmin env.sample 的用法
    可以方便配合 Git 的现代编辑器
    运算放大器复习
    Linux 权限使用 777 真的好吗?
  • 原文地址:https://www.cnblogs.com/bruce1992/p/14019592.html
Copyright © 2011-2022 走看看