创建 EventHandler 时使用静态修饰符有什么意义?
What is the point of using static modifier when creating an EventHandler?
考虑以下来自 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");
}
}
使用静态修饰符有什么意义?
由于您是从静态方法 (Main
) 进行事件订阅的,因此您可以直接使用静态方法作为事件处理程序。
否则你需要一个 class:
的实例
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");
}
}
考虑以下来自 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");
}
}
使用静态修饰符有什么意义?
由于您是从静态方法 (Main
) 进行事件订阅的,因此您可以直接使用静态方法作为事件处理程序。
否则你需要一个 class:
的实例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");
}
}