2016-04-24 66 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"); 
    } 
} 
相關問題