zoukankan      html  css  js  c++  java
  • c#中的委托和事件

    1.委托

    相当于c++中的函数指针  指针-->委托

    方法作为参数 委托来接受  即委托指向该方法

    委托作用:将方法变成和基本的数据类型一样 可以当参数传递,作为返回值,赋值等

    例子:

    委托声明

    1)delegate void  delegateFun1(int a,float b)  //带参数不带返回值

    2)delegate bool delegateFun2() //不带参数带返回值

    3)delegate bool delegateFun3(int a,int b)//带参数和返回值

    委托实例化

    void fun1(int a,float b)

    {

      ...

    }

    1) delegateFun1 f1=new delegateFun1(fun1)

    2)delegateFun1 f2=fun1;

    3)

      delegateFun1 f3; 

      f3=fun1;

       f3+=fun2;//多播委托  委托内部就是一个数组

    实际上使用+=符号的时候会判断
    如果此时委托还没有实例化(委托实例为null),它会自动用+=右边的函数实例化委托
    如果此时委托已经实例化,它会只把+=右边的函数注册到委托实例上

    匿名函数初始化委托

    delegateFun3 f4 =deleagte(int a,int b){

      ...

    };

    labmda表达式 用在委托中替换匿名函数

    delegateFun3 f4 =(int a,int b)=>{return a+b}

    delegateFun3 f4 =(a,b)=>{return a+b}//进一步简化

    泛型委托(广泛使用)

    1)Action<T>  //带参数无返回值的委托

    2)Fun<T,TResult>  //带参数必须有返回值的委托

    泛型委托的使用(一般结合lambda表达式使用)

    Action泛型委托原理 public delegate void Action(T)

    Func泛型委托原理 public delegate TResult Func(T,out Result)

    Action f5=()=>{Console.WriteLine("...");}//无参数无返回值的泛型委托

    Action<int,int> f6=(int a,int b)=>{Console.WriteLine("123");}//带参数无返回值的泛型委托

    Action<int,int> f7=(a,b)={...};

    Func<string> f8=()=>{return "123";}//

    Func<int,string> f9=(int a)=>{return "2222";};

    Func<int,string,bool>=(int a,string s)=>{return true;}

    2.事件

    c#事件定义  public event DelegateFun checkEvent;

    使用步骤: 声明事件->实例化事件->注册函数到事件

    事件和委托的关系:事件就是经过封装的委托

    事件使用要点

    delegate void DelegateFun(int a);

    1.不用判空  if(delegate!=null)

    2. 不能用'='实例化只能用+=初始化 用'='会出错

     

    3.在类的内部,无论声明是protected还是public,都是private 封装性良好,防止外部访问

  • 相关阅读:
    angularJS---初识指令
    Bootstrap ACE后台管理界面模板-jquery已整理
    memcached和redis的区别和应用场景
    微信开发,公众号支付及微信扫描支付各自使用的密码分别来自哪里
    微信 redirect_uri参数错误 正确的处理
    jquery jsonp实现跨域
    php 常用的好函数(持续更新)
    pre 随变化的样式
    CSS 居中 可随着浏览器变大变小而居中
    2017.03.02-2017.09.28 日常随笔
  • 原文地址:https://www.cnblogs.com/lt123/p/6706108.html
Copyright © 2011-2022 走看看