007委托和事件

委托:

  委托是什么?
    1. 本身是一个类, 继承自System.MulticastDelegate, 同时System.MulticastDelegate又继承了Delegate
    2. 委托在实例化的时候, 必须传递一个参数, 参数就是方法的名称; 但是这个方法的签名(返回值类型, 参数个数)必须和委托定                   义的保持一致
    3. 调用的时候, 像类一样调用; 但是是用实例化名加上.Invoke()来调用; 这个Invoke就是父类(System.MulticastDelegate)的                       方法 [反编译使用IL就能看到]

public delegate void NoReturnNoPara(); //1 声明委托
NoReturnNoPara method = new NoReturnNoPara(this.DoNothing);//2 委托的实例化
//通过反编译工具ILspy, 可以发现委托反编译之后就是一个类, 然后继承了一个叫[mscorlib]System.MulticastDelegate的方法; 所以这里可以直接调用invoke
method.Invoke();//3 委托实例的调用
method(); //当然可以省略掉 Invoke(); 都等同于 直接调用 DoNothing这个方法

委托做什么?
  1. 把方法包装成变量, 在执行委托的时候, 才开始调用

    /// <summary>
    /// 定义一个委托
    /// </summary>
    /// <param name="student"></param>
    /// <returns></returns>
    public delegate bool ThanDelegate(Student student);



    /// <summary> /// 1 type:不同的值 不同的判断 如果再多一种 /// /// 传个参数--判断参数--执行对应的行为 /// 能不能直接传递个行为呢?逻辑就是方法,等于说是传递方法进来 /// student.Age > 25 这里我们只需要传递这个逻辑 /// </summary> /// <param name="source"></param> /// <returns></returns> private List<Student> GetList(List<Student> source, int type) { List<Student> result = new List<Student>(); foreach (Student student in source) { if (type == 1) { if (student.Age > 25)//判断条件 { result.Add(student);//满足条件的放入容器 } } else if (type == 2) { if (student.Name.Length > 2) { result.Add(student); } } else if (type == 3) { if (student.Name.Length > 2 && student.Age > 25 && student.ClassId == 2) { result.Add(student); } } } return result; } /// <summary> /// 判断逻辑传递进来+实现共用逻辑 /// 委托解耦, 公共逻辑和业务逻辑的耦合, 减少重复代码 /// </summary> /// <param name="source"></param> /// <param name="method"></param> /// <returns></returns> private List<Student> GetListDelegate(List<Student> source, ThanDelegate method) { List<Student> result = new List<Student>(); foreach (Student student in source) { if (method.Invoke(student)) { result.Add(student); } } return result; }

  

猜你喜欢

转载自www.cnblogs.com/wxylog/p/9602589.html