Action和Func委托 委托的多播 匿名函数 箭头函数

一,Action委托表示一个void返回类型的方法 不需要定义委托

           MyDelegate myDelegate   =new MyDelegate (ProgramMothod);
            myDelegate();

            Action myAction = new Action (ProgramMothod);//Action方法
            myAction ();

二,Func委托表示一个带返回类型的方法

MyDelegate3 myDelegate3 = new MyDelegate3(ProgramMothod1);
            myDelegate3();
            Func<string> func = new Func<string>(ProgramMothod1);
            func();

如果有参数 返回值类型在最后

 Func<int,string> func1 = new Func<int ,string>(ProgramMothod2);
            string tempStr1  = func1 (10);
            Console.WriteLine(tempStr1);

 private static string ProgramMothod2(int a)
        {

            return a.ToString();

        }
三,委托的多播
1.方法的类型相同
2.同时执行
3.委托对象利用+=方式 完成多播的使用   -=取消多播操作

 MyDelegate myDelegate2 = new MyDelegate(ProgramMothod);

  myDelegate2 += ProgramMothod1;
  myDelegate2();//同时执行ProgramMothod 和ProgramMothod1函数
   myDelegate2 -= ProgramMothod1;
  myDelegate2();//没有ProgramMothod1函数 只执行ProgramMothod

Action 多播 也可以用同样的方法 也可以

四,Action 泛型 

 Action<int> action = new Action<int>(ProgramMothod1);

  private static void ProgramMothod1(int a)
        {

            Console.WriteLine(a);

        }

 Action<int, string[]> action2 = new Action<int, string[]>(ProgramMothod3);

  private static void ProgramMothod3<T, W>(T a, W[]array)
        {
            Console.WriteLine(a);
        }

五,函数里面传函数

//使用 Action

Action action = new Action(ProgramMothod1);
            Func<int> func = new Func<int>(ProgramMothod2);//有返回值 返回值是int 形式
         
            ProgramMothod(10, action ,func);
            Console.ReadKey();

//函数

static void ProgramMothod(int a,Action action,Func<int> func) {

            Console.WriteLine(a);
            action();
            func();

        }

        static void ProgramMothod1() {

            Console.WriteLine("123");
        }
        static int ProgramMothod2()
        {

            Console.WriteLine("456");
            return 123;
        }

六,匿名函数

1.事件基于委托的,可以为任何一种委托提供一种发布\订阅机制。(类似委托多播)

   public delegate void BoilHandle(int x);//声明关于事件的委托
        
   2.使用 event 关键字将一个委托类型定义为事件  事件就是委托的一个对象

public event  BoilHandle boilHandle;

1.针对委托的使用
2.可以快捷的使委托实例

3.不建议再使用匿名函数,C#3.0后使用lambda表达式替代普通匿名函数
 4.格式 : 委托对象 = delegate (){};

普通方法

MyDelegate myDelegate = new MyDelegate(ProgramMothod);

 private static int ProgramMothod(int a, int b)
        {

            return a + b;
        }

匿名函数

 MyDelegate myDelegate1 = delegate (int a, int b){ return a - b;};

1.普通匿名函数的升级版本  (箭头函数)
2.比普通匿名函数更为简洁,数据类型可以不用写
MyDelegate myDelegate1= (a,b) => { return a + b; };

  MyDelegate1 myDelegate2 = () => { return 1; };

无参无返回值匿名函数
 Action action = () => { };

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值