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();
    }
    }
  • 相关阅读:
    微信坚硬的后脚跟
    [项目整理]Win32,MFC的可执行文件只能运行一次
    美司法部索要维基解密志愿者谷歌账户内容
    QML性能
    OSGi 的核心配置、动态化及问题
    OSGi 的由来和本质特性
    机器视觉与计算机视觉
    人工智能与深度学习
    活着就能改变世界
    选择与执行
  • 原文地址:https://www.cnblogs.com/cnbwang/p/1924071.html
Copyright © 2011-2022 走看看