C#泛型委托理解(Deleagte与Action、Func用法)



泛型委托,可以分开看,是泛型和委托的组合。

泛型:是将不确定的类型预先定义下来的一种C#高级语。

委托:这个比较简单,从delegate关键字到匿名委托方法,再到Action和Func,Action是无返回值的委托,Func是有返回值的委托,现在基本上都是基于Action和Func来写委托的,有些和业务逻辑连接起来写匿名委托方法。

Delegate:是封装的方法可以有也可以没有返回值。

Action:是.NET Framework内置的泛型委托,无参数返回。

Func:是.NET Framework内置的泛型委托,有参数返回。

现在我们用Delegate自己定义一下泛型委托,便于理解:


        //声明泛型委托,无返回值
        public delegate void myGenericDelegate1<T1, T2>(T1 a, T2 b);
        //声明泛型委托,有返回值从
        public delegate T3 myGenericDelegate2<T1, T2 ,T3>(T1 a, T2 b,T3 c);

        //使用泛型委托,无返回值
        public static myGenericDelegate1<int, int> genericDele1 = delegate (int a1, int a2)
           {
               int result = a1 + a2;
               Console.WriteLine("泛型委托myGenericDelegate1调用的方法:" + result);
           };
        //使用泛型委托,有返回值
        public static myGenericDelegate2<int, int,string> genericDele2 = delegate (int a1, int a2,string a3)
           {
               return "泛型委托myGenericDelegate1调用的方法,带有返回值:"+a1 + a2;
           };

我们再Action和Func实现一下上述代码:

其实C#已经帮我们封装好了泛型委托,无返回值泛型委托Action,有返回值泛型委托Func。

Func和Action相同点 :   都是0~16个参数 

Func和Action不同点 :   Func是有返回值的 而Action没有 

Func编写格式解析如下(注意最后一位是返回值):

  • Func< T1 > (有返回值)------无参数类型,T1为返回值类型

  • Func<T1,T2>(有返回值)------T1为0-16个参数类型,T2为返回值类型

  • Func<T1,T2,T3>(有返回值)------T1和T2为0-16个参数类型,T3为返回值类型

  • 也就是说 参数最后一位就是返回值类型(返回值的类型和Func输出参数类型相同
    Func<int【参数类型】,……,bool【最后一个是返回值类型】】> func

        //系统提供了现成的泛型委托
        //Action泛型委托,无返回值
        //Func泛型委托,有返回值  
        public static Action<int, int> action1 = (a1, a2) =>
        {

            int result = a1 + a2;
            Console.WriteLine("泛型委托Action调用的方法:" + result);

        };

        //Func泛型委托,最后一个参数表示返回值
        public static Func<int, int, string> func1 = (a1, a2) =>
        {

            return "泛型委托Func调用的方法:" + a1 + a2;
        };
 

调用示例及结果:

            GenericTest.genericDele1(1, 2);
            string result1 = GenericTest.genericDele2(1, 2, "");
            Console.WriteLine(result1);
            GenericTest.action1(1, 2);
            string result2 = GenericTest.func1(1, 2);
            Console.WriteLine(result2);
            Console.ReadKey();


 

  • 21
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值