2011-11-22 53 views
0

如果一個類聲明瞭一個事件,那麼只能從該類中觸發事件。限制事件調用的原因是什麼?事件調用

using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

namespace ConsoleApplication12 
{ 
    delegate void Function(); 

    class EventHandling 
    { 
     public event Function fun; 

     public void AddEvents(Function events) 
     { 
      fun += events; 
     } 

     public void Notify() 
     { 
      fun(); 
     } 
    } 

    class Program 
    { 

     static void Main(string[] args) 
     { 
      EventHandling aEvtHandler = new EventHandling(); 
      Function aFun = new Function(Display); 
      aEvtHandler.AddEvents(aFun); 
      aEvtHandler.Notify(); 
     } 

     static void Display() 
     { 
      Console.WriteLine("in the display"); 
      Console.Read(); 
     } 
    } 
} 

回答

1

從定義它的類中引發一個事件是有意義的。

如果我創建一個自行車類,並且該類包含EngineStarted事件,那麼該事件何時引發?發生什麼事情可以使發動機啓動。所以,事件被解僱意味着類的實例(一個Bike對象)向外界報告引擎已經啓動。

沒有意義的是,另一個對象會向世界報告特定自行車的引擎已經啓動,而自行車本身並沒有先報告。