2016-04-24 63 views
-1

考虑从dotnetperls下面的例子:创建EventHandler时使用静态修饰符有什么意义?

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"); 
} 
} 

什么是使用static修饰符的地步?

+2

因为你使用它的静态方法 - 静态无效的主要() – User1234

回答

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"); 
    } 
} 
相关问题