事件和委托经常连在一起说,然后就不知道他们两个具体有什么区别了。今天特意在网上搜了一下,把收集的一点资料整理一下,以防自己忘记了。
1. 委托在C#中其实也是一个类,用反编译工具可看到委托是System.MulticastDelegate的子类,类中定义了一个构造函数、一个Invoke方法、两个异步方法(BeginInvoke/EndInvoke)
2. 事件是一个特殊的委托对象,用event关键字声明,类事件成员只能在类内部调用,委托则可以在类外部调用
/// <summary>
/// 事件与委托的demo
/// </summary>
public class EventAndDelegate
{
public void Run()
{
Teacher t = new Teacher() { Name = "mike" };
Student s = new Student();
t.Say += s.Say;
t.Say2 += this.SaySomeThing;
t.Say2("hello");//类成员委托可以在类外部调用
//t.Say("");//类成员事件不能在类外部调用
Teacher.Say_Static += this.SaySomeThing;
Teacher.Say_Static("hello 2");
Teacher.Say_Static_Event += this.SaySomeThing;
//Teacher.Say_Static_Event("");//静态事件成员也不能在类外部调用
t.Meet();
}
public void SaySomeThing(string str)
{
Console.WriteLine(str);
}
}
public delegate void SayHello(string str);
public class Teacher
{
public SayHello Say2;
public event SayHello Say;
public static SayHello Say_Static;
public static event SayHello Say_Static_Event;
public string Name;
public void Meet()
{
string str = string.Format("hello {0}", Name);
if (Say != null)
Say(str);
if (Say2 != null)
Say2(str);
if (Say_Static != null)
Say_Static(str);
if (Say_Static_Event != null)
Say_Static_Event(str);
}
}
public class Student
{
public void Say(string name)
{
Console.WriteLine("hello " + name);
}
}