通过一个例子理解泛型委托的好处

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

解决问题:对这组数指定位置取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

吾生也有涯,而知也无涯,以有涯随无涯,殆已。
原文地址:https://www.cnblogs.com/kcir/p/11475213.html