阅读msdn的事件描述和示例,我可以看到订阅事件的方式存在差异。有时事件处理程序是“按原样”传递的,有时它们是通过使用处理程序方法实例化委托来传递的,例如
...
class Subscriber
{
private string id;
public Subscriber(string ID, Publisher pub)
{
id = ID;
// Subscribe to the event using C# 2.0 syntax
pub.RaiseCustomEvent += HandleCustomEvent;
}
// Define what actions to take when the event is raised.
void HandleCustomEvent(object sender, CustomEventArgs e)
{
Console.WriteLine(id + " received this message: {0}", e.Message);
}
}
对比
public delegate void EventHandler1(int i);
...
public class TestClass
{
public static void Delegate1Method(int i)
{
System.Console.WriteLine(i);
}
public static void Delegate2Method(string s)
{
System.Console.WriteLine(s);
}
static void Main()
{
PropertyEventsSample p = new PropertyEventsSample();
p.Event1 += new EventHandler1(TestClass.Delegate1Method);
p.RaiseEvent1(2);
...
}
}
有人可以澄清一下吗?
谢谢。