1. 如下例子说明Delegate关键字的意义(相当于声明一个具有函数指针功能的类)
class Program
{
//delegate声明
public delegate void MyDelegate(string input);
/// <summary>函数1</summary>
/// <param name="input"></param>
public static void Hello1(string input)
{
Console.WriteLine("invoked1:" + input);
}
/// <summary>函数2</summary>
/// <param name="input"></param>
public static void Hello2(string input)
{
Console.WriteLine("invoked2:" + input);
}
static void Main(string[] args)
{
MyDelegate d1 = new MyDelegate(Hello1);
MyDelegate d2 = new MyDelegate(Hello2);
//可以组合delegate对象
MyDelegate d3 = d1 + d2;
d3("trigger");
}
}
结果:invoked1:trigger
invoked2:trigger
2. Event的本质相当于一个修饰符
2.1 Event修饰的字段可以声明在接口里面
public delegate void MyDelegate(string input);
interface eventTest {
event MyDelegate myEvent;
}
2.2 Event的触发只能从定义它的类当中触发(通过查看IL)
public static MyDelegate myDelegate;
public static event MyDelegate myEvent;
.field public static class ConsoleApplication2.Program/MyDelegate myDelegate
.field private static class ConsoleApplication2.Program/MyDelegate myEvent
说明:IL代码显示myEvent被声明为私有类,所以只能从定义它的类中触发event