一、委托
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ConsoleCSharp
{
public delegate void compute(int a, int b);
class Program
{
static void Main(string[] args)
{
//compute c = add;
compute c = new compute(add);
c += mimus;
c += multiply;
c(3, 5);
}
public static void add(int a, int b)
{
Console.WriteLine("{0} add {1} is {2}", a, b, a + b);
}
public static void mimus(int a, int b)
{
Console.WriteLine("{0} mimus {1} is {2}", a, b, a - b);
}
public static void multiply(int a, int b)
{
Console.WriteLine("{0} multiply {1} is {2}", a, b, a * b);
}
}
}
二、事件
1、C#事件是特殊的委托
2、C#中使用委托模型来实现事件的。
3、C#中的委托是一个引用类型,可以把它看成一个特殊的”类”。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ConsoleCSharp
{
class Program
{
static void Main(string[] args)
{
Employee emp = new Employee();
HumanResource hr = new HumanResource();
MyEventArgs e = new MyEventArgs(12.25);
emp.OnSalayCompute += new SalayCompute(hr.salayComputeHandle); //注册
for ( ; ; )
{
Thread.Sleep(1000);
emp.FireEvent(e);
}
}
}
public delegate void SalayCompute(object sender, MyEventArgs e); //声明一个代理类
class Employee
{
public event SalayCompute OnSalayCompute; //定义事件,将其与代理绑定
public void FireEvent(MyEventArgs e) //触发事件的方法
{
if (OnSalayCompute != null)
{
OnSalayCompute(this, e); //触发事件
}
}
}
public class MyEventArgs : EventArgs //定义事件参数类
{
public readonly double _salary;
public MyEventArgs(double salary)
{
this._salary = salary;
}
}
class HumanResource
{
//事件处理函数,签名应与代理一致
public void salayComputeHandle(object sender, MyEventArgs e)
{
Console.WriteLine("salay: {0}", e._salary);
}
}
}