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();
    }
    }
  • 相关阅读:
    export,source
    zookeeper安装笔记
    centos修改启动顺序,登录后提示,启动级别,主机名,免密登录
    CentOS卸载系统自带的OpenJDK
    处理有外键约束的数据
    linux iptables
    centos httpd服务做yum本地源,以及安装Mysql
    Linux命令(一)grep查询
    LaTeX符号和图片
    LaTeX文章结构
  • 原文地址:https://www.cnblogs.com/cnbwang/p/1924071.html
Copyright © 2011-2022 走看看