zoukankan      html  css  js  c++  java
  • 通过迭代器为序列创建可组合的API

    通常,对于一个集合的操作会封装多个逻辑

    如果将这些逻辑全部写在一个循环里面,那么逻辑本身的可重用性就大打折扣。

    如果讲每个逻辑都单独写个循环,那么程序的性能就会收到影响。

    那么该如何做呢?幸好有延迟执行(deffered execution model)模型。代码如下。

    class Program
    {
    static void Main()
    {
    int[] arrint = { 3, 5, 1, 3, 6, 4, 2, 1, 6 };
    foreach (var item in Square(Unique(arrint)))
    {
    Console.WriteLine(
    "arrint " + item);
    }

    MyControl[] arrcon
    = { new MyControl(1, "aaa"), new MyControl(2, "bbb"), new MyControl(2, "bbb"), new MyControl(3, "ccc") };
    foreach (var item in Square(Unique(arrcon)))
    {
    Console.WriteLine(
    "arrcon " + item);
    }

    }
    static IEnumerable<T> Unique<T>(IEnumerable<T> nums)
    {
    Dictionary
    <string, T> uniqueVals = new Dictionary<string, T>();
    foreach (T num in nums)
    {
    if (!uniqueVals.ContainsKey(num.ToString()))
    {
    uniqueVals.Add(num.ToString(), num);
    yield return num;
    }
    }
    }

    static IEnumerable<Int32> Square<T>(IEnumerable<T> nums)
    {
    foreach (var item in nums)
    {
    yield return Int32.Parse(item.ToString()) * Int32.Parse(item.ToString());
    }
    }
    }
    class MyControl
    {
    public int MaxLength { get; set; }
    public string Text { get; set; }
    public MyControl(int l, string t)
    {
    this.MaxLength = l;
    this.Text = t;
    }
    public int GetLength()
    {
    return this.MaxLength;
    }
    public override string ToString()
    {
    return this.MaxLength.ToString();
    }
    }
  • 相关阅读:
    移动端调试Vconsole
    Vue-返回顶部
    Vue-封装loading
    Vue-水印封装
    Vue-封装scroll触底
    微信小程序-图片上传
    前端面试题(2)
    前端常见面试题
    服务端渲染(SSR)和客户端(CSR)渲染的区别
    什么是模块化?模块化开发的好处
  • 原文地址:https://www.cnblogs.com/cnbwang/p/1924071.html
Copyright © 2011-2022 走看看