Amor-ztt

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

委托:是一种类型,可“持有”多个方法,可以看作一个方法串(eg 糖葫芦)
委托相当于c++中的函数指针

在c#中,在类外,想要调用一个方法有两种方式
第一种:通过方法名。 1、实例名.方法名(实例方法) 2、类名.方法名(静态方法)
第二种:委托方式。

委托有两种类型
1、自定义委托 eg: delegate 返回值类型 委托名字(参数列表)
(注意!!因为委托是方法的包装器,所以参数列表中的参数是 方法!或委托! )
2、系统内置委托
常见的有
Action 泛型委托。(有参,无返回值)
Func泛型委托。(有参,有返回值)

委托的优点
1、可以通过一次操作,实现不同结果(多态思想)
通过不同的委托去调用同一个泛型方法,从而实现不同的结果

2、可以一次调用多个方法(多播),用“委托2+=委托1”

 `
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace myDelDemo1
{
    class Program
    {
        static void Main(string[] args)
        {
            Program p1 = new Program();
            //MyDele<int> sumDele=new MyDele<int>(p1.Sum);
            Action<int,int> actionSum =new Action<int,int>(Add);
            actionSum(1,1);

            //泛型方法+泛型委托,可以实现,调用同一个方法,产生不同的结果
            var actionSum2 = new Action<string, string>(p1.Sum2);
            actionSum2("hello", "world");

            var actionSum3 = new Action<int, int>(p1.Sum2);
            actionSum3(9, 0);

            Func<int,int,int> funcAdd =new Func<int, int, int>(p1.Sum);
            Console.WriteLine(funcAdd(2,8));

            //MyDele<double> doubleDele = new MyDele<double>(Mul);
            var funcMul= new Func<double, double, double>(Mul);  //var简写形式
            Console.WriteLine(funcMul(2.2,3.3));
        }
     //   delegate T MyDele<T>(T a, T b);

        static void Add(int a ,int b)
        {
            Console.WriteLine($"{a}+{b}");
        }
        public int Sum(int a,int b)
        {
            return a + b;
        }
        public void Sum2<T>(T a, T b)
        {
            Console.WriteLine("{0} and {1}",a,b);
        }
        static public double Mul(double a , double b)
        {
            return a * b;
        }
    }
}

posted on 2023-04-05 18:28  小颜七七  阅读(127)  评论(0)    收藏  举报