C#-委托

2018-04-27  本文已影响28人  _小圆球_

委托

声明委托

委托使用

private delegate string GetAString();

static void Main(){
    int x = 40;
    GetAString firstStringMethod = new GetAString(x.ToString);
    Console.WriteLine(firstStringMethod());
}

委托的赋值

简单委托示例

class MathOperations{
    public static double MultiplyByTwo(double value){
        return value*2;
    }
    public static double Square(double value){
        return value*value;
    }
}
delegate double DoubleOp(double x);
static void Main(){
    DoubleOp[] operations={ MathOperations.MultiplyByTwo,MathOperations.Square };
    for(int i =0;i<operations.Length;i++){
        Console.WriteLine("Using operations "+i);
        ProcessAndDisplayNumber( operations[i],2.0 );
    }
}
static void ProcessAndDisplayNumber(DoubleOp action,double value){
    double res = action(value);
    Console.Writeline("Value :"+value+" Result:"+res);
}

Action委托和Func委托

案例1

案例2-对int类型排序

bool swapped = true;
do{
    swapped = false;
    for(int i =0;i<sortArray.Length -1;i++){
        if(sortArray[i]>sortArray[i+1]){
            int temp= sortArray[i];
            sortArray[i]=sortArray[i+1];
            sortArray[i+1]=temp;
            swapped = true;
        }
    }
}while(swapped);

案例2-雇员类

class Employee{
    public Employ(string name,decimal salary){
        this.Name = name;
        this.Salary = salary;
    }
    public string Name{get;private set;}
    public decimal Salary{get;private set;}
    public static bool CompareSalary(Employee e1,Employee e2){
        return e1.salary>e2.salary;
    }
}

案例2-通用的排序方法

public static void Sort<T>( List<T> sortArray,Func<T,T,bool> comparision ){
    bool swapped = true;
    do{
        swapped = false;
        for(int i=0;i<sortArray.Count-1;i++){
            if(comparision(sortArray[i+1],sortArray[i])){
                T temp = sortArray[i];
                sortArray[i]=sortArray[i+1];
                sortArray[i+1]=temp;
                swapped = true;
            }
        }
    }while(swapped);
}

案例2-对雇员类排序

static void Main(){
    Employee[] employees = {
        new Employee("Bunny",20000),        
        new Employee("Bunny",10000),        
        new Employee("Bunny",25000),        
        new Employee("Bunny",100000),       
        new Employee("Bunny",23000),        
        new Employee("Bunny",50000),
        };
    Sort(employees,Employee.CompareSalary);
    // 输出
}

多播委托

Action a1 = Method1;
a1+=Method2;

Delegate[] delegates=a1.GetInvocationList();
foreach(delegate d in delegates){
    //d();
    d.DynamicInvoke(null);
}
// 遍历多播委托中所有的委托,然后单独调用

匿名方法

Func<int,int,int> plus = delegate (int a,int b){
    int temp = a+b;
    return temp;
};
int res = plus(34,34);
Console.WriteLine(res);

Lambda表达式-表示一个方法的定义

  Func<int,int,int> plus = (a,b)=>{ int temp= a+b;return temp; };
  int res = plus(34,34);
  Console.WriteLine(res);

多行语句

Func<double,double> square = x=>x*x;
    // 添加花括号,return语句和分号是完全合法的
    Func<double,double> square = x=>{
        return x*x;
        }

Lambda表达式外部的变量

int somVal = 5;
Func<int,int> f = x=>x+somVal;
Console.WriteLine(f(3));//8
somVal = 7;
Console.WriteLine(f(3));//10

事件

Cat类和Mouse类
      class Cat
      {
          string catName;
          string catColor { get; set; }
          public Cat(string name, string color)
          {
              this.catName = name;
              catColor = color;
         }
         public void CatShout()
         {
             Console.WriteLine(catColor+" 的猫 "+catName+" 过来了,喵!喵!喵!\n");
             //猫叫时触发事件
             //猫叫时,如果CatShoutEvent中有登记事件,则执行该事件
             if (CatShoutEvent != null)
                 CatShoutEvent();
         }
         public delegate void CatShoutEventHandler();
         public event CatShoutEventHandler CatShoutEvent;
     }
     class Mouse
     {
         string mouseName;
         string mouseColor { get; set; }
         public Mouse(string name, string color)
         {
             this.mouseName = name;
             this.mouseColor = color;
         }
         public void MouseRun()
         {
             Console.WriteLine(mouseColor + " 的老鼠 " + mouseName + " 说:\"老猫来了,快跑!\"  \n我跑!!\n我使劲跑!!\n我加速使劲跑!!!\n");
         }
     }
运行代码结果
              Console.WriteLine("[场景说明]: 一个月明星稀的午夜,有两只老鼠在偷油吃\n");
              Mouse Jerry = new Mouse("Jerry", "白色");
              Mouse Jack = new Mouse("Jack", "黄色");
              
              Console.WriteLine("[场景说明]: 一只黑猫蹑手蹑脚的走了过来\n");
              Cat Tom = new Cat("Tom", "黑色");
              Console.WriteLine("[场景说明]: 为了安全的偷油,登记了一个猫叫的事件\n");

             Tom.CatShoutEvent += new Cat.CatShoutEventHandler(Jerry.MouseRun);
             Tom.CatShoutEvent += new Cat.CatShoutEventHandler(Jack.MouseRun);


             Console.WriteLine("[场景说明]: 猫叫了三声\n");
             Tom.CatShout();
             Console.ReadKey();

事件与委托的联系和区别
上一篇 下一篇

猜你喜欢

热点阅读