zoukankan      html  css  js  c++  java
  • 通过一个例子理解泛型委托的好处

    最近学泛型委托,看到这个例子比较好,记录一下。通过解决下面的问题,体现泛型委托的好处

    解决问题:对这组数指定位置取3个数,求和求积 (10, 9, 8, 7, 6, 5, 4, 3, 2)

    普通方法:调用两个求和,求积的方法

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace DelegateDemo
    {
        class Program
        {
            static void Main(string[] args)
            {
                //对这组数指定位置取3个数,求和求积
                int[] nums = { 10, 9, 8, 7, 6, 5, 4, 3, 2 };
    
                //输出结果
                Console.WriteLine(calSum(nums, 0, 3));
                Console.WriteLine(calQuadrature(nums, 0, 3));
    
                Console.ReadLine();
            }
            
            //求和
            static int calSum(int[] nums,int from ,int to)//(数组、起始位置、结束位置)
            {
                int result = 0;
                for (int i = from; i <= to; i++)
                {
                    result += nums[i];
                }
                return result;
            }
            //求积
            static int calQuadrature(int[] nums, int from, int to)
            {
                int result = 1;
                for (int i = from; i <= to; i++)
                {
                    result *= nums[i];
                }
                return result;
            }
        }
    }

    泛型委托:把委托作为方法的参数,就好像替换了“运算符”一样简单

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace DelegateDemo
    {
        class Program
        {
            static void Main(string[] args)
            {
                //对这组数指定位置取3个数,求和求积
                int[] nums = { 10, 9, 8, 7, 6, 5, 4, 3, 2 };
    
                //输出结果
                Console.WriteLine(CommonMethod((a, b) => a + b, 0, 3, nums));//参数说明(lambda表达式、开始、结束位置、数组)
                Console.WriteLine(CommonMethod((a, b) => a * b, 0, 3, nums));
                Console.ReadLine();
            }
            //定义一个方法,传递“运算符”
            static int CommonMethod(Func<int,int,int> operation ,int from ,int to,int[] nums)
            {
                int result = nums[from]; //获取第一个数
                for (int i = from+1; i <= to; i++)
                {
                    result = operation(result, nums[i]);//根据委托运算
                }
                return result;
            }
        }
    }

    输出结果都是:

    34
    5040

    吾生也有涯,而知也无涯,以有涯随无涯,殆已。
  • 相关阅读:
    一道亲戚的生物学改题
    【水】强化16题解
    【我为标程写注释】最大值最小化
    【我为标程写注释】卢斯进制
    oracle 解锁表
    Oracle存储过程根据指定日期返回(N个)工作日的时间
    NPOI_2.1.3_学习记录(6)-Excel中设置小数、百分比、货币、日期、科学计数法和金额大写
    NPOI_2.1.3_学习记录(5)-创建Excel的页眉页脚
    NPOI_2.1.3_学习记录(4)-Excel中单元格的复制
    NPOI_2.1.3_学习记录(2)-在Excel中创建工作表(Sheet)
  • 原文地址:https://www.cnblogs.com/kcir/p/11475213.html
Copyright © 2011-2022 走看看