delegate是C#中的一种类型,它实际上是一个能够持有对某个方法的引用的类。与其它的类不同,delegate类能够拥有一个签名(signature),并且它”只能持有与它的签名相匹配的方法的引用“。它所实现的功能与C/C++中的函数指针十分相似。它允许你传递一个类A的方法m给另一个类B的对象,使得类B的对象能够调用这个方法m。但与函数指针相比,delegate有许多函数委托和事件在 .Net Framework中的应用非常广泛指针不具备的优点。首先,函数指针只能指向静态函数,而delegate既可以引用静态函数,又可以引用非静态成员函数。在引用非静态成员函数时,delegate不但保存了对此函数入口指针的引用,而且还保存了调用此函数的类实例的引用。其次,与函数指针相比,delegate是面向对象、类型安全、可靠的受控(managed)对象。也就是说,runtime能够保证delegate指向一个有效的方法,你无须担心delegate会指向无效地址或者越界地址。
实现一个delegate是很简单的,通过以下3个步骤即可实现一个delegate:
1、声明一个delegate对象,它应当与你想要传递的方法具有相同的参数和返回值类型。
2、创建delegate对象,并”将你想要传递的函数作为参数传入”。
3、在要实现异步调用的地方,通过上一步创建的对象来调用方法。
using System;
public class MyDelegateTest
{
// 步骤1,声明delegate对象
public delegate void MyDelegate(string name);
// 这是我们欲传递的方法,它与MyDelegate具有相同的参数和返回值类型
public static void MyDelegateFunc(string name)
{
Console.WriteLine("Hello, ", name);
}
public static void Main()
{
// 步骤2,创建delegate对象(实例??)
MyDelegate md = new MyDelegate(MyDelegateTest.MyDelegateFunc);
// 步骤3,调用delegate
md("sam1111");
}
}
输出结果是:Hello, sam1111
了解了delegate,下面我们来看看,在C#中对事件是如何处理的。
C#中的事件处理实际上是一种具有特殊签名的delegate,象下面这个样子:
public delegate void CalculateEventHandler(object sender, MyEventArgs e);
其中的两个参数,sender代表事件发送者,e是事件参数类。MyEventArgs类用来包含与事件相关的数据,所有的事件参数类都必须从System.EventArgs类派生。当然,如果你的事件不含参数,那么可以直接用System.EventArgs类作为参数。
就是这么简单,结合delegate的实现,我们可以将自定义事件的实现归结为以下几步:
1、定义delegate对象类型,它有两个参数,第一个参数是事件发送者对象,第二个参数是事件参数类对象。
2、定义事件参数类,此类应当从System.EventArgs类派生。如果事件不带参数,这一步可以省略。
3、定义”事件处理方法,它应当与delegate对象具有相同的参数和返回值类型”。
4、用event关键字定义事件对象,它同时也是一个delegate对象。
5、用+=操作符添加事件到事件队列中(-=操作符能够将事件从队列中删除)。
6、在需要触发事件的地方用调用delegate的方式写事件触发方法。一般来说,此方法应为protected访问限制,既不能以public方式调用,但可以被子类继承。名字是OnEventName。
7、在适当的地方调用事件触发方法触发事件。
public class Calculator
{
/// <summary>
/// 定义一个CalculateEventArgs
/// 用于存放事件引发时向处理程序传递的状态信息
/// </summary>
public class CalculateEventArgs : EventArgs
{
public readonly int x, y;
public CalculateEventArgs(int x, int y)
{
this.x = x;
this.y = y;
}
}
//声明事件委托
public delegate void CalculateEventHandler(object sender, CalculateEventArgs e);
//定义事件成员,提供外部绑定
public event CalculateEventHandler MyCalculate;
//提供受保护的虚方法,可以由子类覆写来拒绝监视
public virtual void OnCalculate(CalculateEventArgs e)
{
if (MyCalculate != null)
{
MyCalculate(this, e);
}
}
//进行计算,调用该方法表示有新的计算发生
public void Calculate(int x, int y)
{
CalculateEventArgs e = new CalculateEventArgs(x, y);
OnCalculate(e);
}
}
一件事件的完整程序就这样定义好了,然后需要一个事件触发程序,用来监听事件:
/// <summary>
/// 定义事件触发者
/// </summary>
public class CalculateManager
{
/// <summary>
/// 定义信息通知方法
/// </summary>
public void Add(object sender, Calculator.CalculateEventArgs e)
{
Console.WriteLine(e.x + "==========" + e.y);
}
public void Substract(object sender, Calculator.CalculateEventArgs e)
{
Console.WriteLine(e.x + "==========" + e.y);
}
}
之后就是实现事件的处理
/// <summary>
///
/// </summary>
public class Test_Calculator
{
public static void Main11()
{
Calculator calculator = new Calculator();
//事件触发者
CalculateManager cm = new CalculateManager();
//事件绑定
calculator.MyCalculate += cm.Add;
calculator.Calculate(100, 200);
calculator.MyCalculate += cm.Substract;
calculator.Calculate(100, 200);
//事件注销
calculator.MyCalculate -= cm.Add;
calculator.Calculate(100, 200);
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
class Program
{
public class Heater
{
private int temperature;
public string type = "RealFire 001"; // 添加型号作为演示
public string area = "China Xian"; // 添加产地作为演示
//声明委托
public delegate void BoiledEventHandler(Object sender, BoiledEventArgs e);
public event BoiledEventHandler Boiled; //声明事件
// 定义BoiledEventArgs类,传递给Observer所感兴趣的信息
public class BoiledEventArgs : EventArgs
{
public readonly int temperature;
public BoiledEventArgs(int temperature)
{
this.temperature = temperature;
}
}
// 可以供继承自 Heater 的类重写,以便继承类拒绝其他对象对它的监视
protected virtual void OnBoiled(BoiledEventArgs e)
{
if (Boiled != null)
{ // 如果有对象注册
Boiled(this, e); // 调用所有注册对象的方法
}
}
// 烧水。
public void BoilWater()
{
for (int i = 0; i <= 100; i++)
{
temperature = i;
if (temperature > 95)
{
//建立BoiledEventArgs 对象。
BoiledEventArgs e = new BoiledEventArgs(temperature);
OnBoiled(e); // 调用 OnBolied方法
}
}
}
}
// 警报器
public class Alarm
{
public void MakeAlert(Object sender, Heater.BoiledEventArgs e)
{
Heater heater = (Heater)sender; //这里是不是很熟悉呢?
//访问 sender 中的公共字段
Console.WriteLine("Alarm:{0} - {1}: ", heater.area, heater.type);
Console.WriteLine("Alarm: 嘀嘀嘀,水已经 {0} 度了:", e.temperature);
Console.WriteLine();
}
}
// 显示器
public class Display
{
public static void ShowMsg(Object sender, Heater.BoiledEventArgs e)
{ //静态方法
Heater heater = (Heater)sender;
Console.WriteLine("Display:{0} - {1}: ", heater.area, heater.type);
Console.WriteLine("Display:水快烧开了,当前温度:{0}度。", e.temperature);
Console.WriteLine();
}
}
static void Main(string[] args)
{
Heater heater = new Heater();
Alarm alarm = new Alarm();
heater.Boiled += alarm.MakeAlert; //注册方法
//heater.Boiled += (new Alarm()).MakeAlert; //给匿名对象注册方法
//heater.Boiled += new Heater.BoiledEventHandler(alarm.MakeAlert); //也可以这么注册
heater.Boiled += Display.ShowMsg; //注册静态方法
heater.BoilWater(); //烧水,会自动调用注册过对象的方法
}
}
}

3917

被折叠的 条评论
为什么被折叠?



