C#的delegate和event关键字
(本文未经许可禁止转载)
delegate
delegate是用来声明“函数指针”的关键词。具有以下特点:
- 定义方式:变量语义
public delegate void Trigger();
- 实例化方式:类语义
//... var trigger1 = new Trigger(PrintA); var trigger2 = new Trigger(PrintB); //...
public void PrintA() => Console.WriteLine("A"); public void PrintB() => Console.WriteLine("B");
- 运算方式:变量语义
运算指:把两个函数指针按照前后调用顺序结合成新的指针。var trigger3 = trigger1 + trigger2; trigger3();
输出
A B
event
event是专门用于修饰delegate变量的修饰词。即,可有如下两种方式声明一个delegate变量
public event Trigger trigger4;
public Trigger trigger5;
event修饰过的delegate有如下几种限定: