2011-11-22 52 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对象)向外界报告引擎已经启动。

没有意义的是,另一个对象会向世界报告特定自行车的引擎已经启动,而自行车本身并没有先报告。