请考虑dotnetperls中的以下示例:
using System;
public delegate void EventHandler();
class Program
{
public static event EventHandler _show;
static void Main()
{
// Add event handlers to Show event.
_show += new EventHandler(Dog);
_show += new EventHandler(Cat);
_show += new EventHandler(Mouse);
_show += new EventHandler(Mouse);
// Invoke the event.
_show.Invoke();
}
static void Cat()
{
Console.WriteLine("Cat");
}
static void Dog()
{
Console.WriteLine("Dog");
}
static void Mouse()
{
Console.WriteLine("Mouse");
}
}
使用静态修饰符有什么意义?
答案 0 :(得分:1)
由于您是从静态方法(Main
)进行事件订阅,因此您可以直接使用静态方法作为事件处理程序。
否则你需要一个类的实例:
using System;
public delegate void EventHandler();
class Program
{
public static event EventHandler _show;
static void Main()
{
var program = new Program();
_show += new EventHandler(program.Dog);
_show += new EventHandler(program.Cat);
_show += new EventHandler(program.Mouse);
_show += new EventHandler(program.Mouse);
// Invoke the event.
_show.Invoke();
}
void Cat()
{
Console.WriteLine("Cat");
}
void Dog()
{
Console.WriteLine("Dog");
}
void Mouse()
{
Console.WriteLine("Mouse");
}
}