代表和活动

我创建了一个非常简单的虚拟程序来理解委托和事件。 在我的下面的程序中,我很简单地调用一个方法。 当我调用一个方法时,在代理和事件的帮助下自动调用五个方法。

请看一下我的程序,并告诉我我错在哪里或者正确,因为这是我第一次使用代表和活动。

using System; namespace ConsoleApplication1 { public delegate void MyFirstDelegate(); class Test { public event MyFirstDelegate myFirstDelegate; public void Call() { Console.WriteLine("Welcome in Delegate world.."); if (myFirstDelegate != null) { myFirstDelegate(); } } } class AttachedFunction { public void firstAttachMethod() { Console.WriteLine("ONE..."); } public void SecondAttachMethod() { Console.WriteLine("TWO..."); } public void thirdAttachMethod() { Console.WriteLine("THREE..."); } public void fourthAttachMethod() { Console.WriteLine("FOUR..."); } public void fifthAttachMethod() { Console.WriteLine("FIVE..."); } } class MyMain { public static void Main() { Test test = new Test(); AttachedFunction attachedFunction = new AttachedFunction(); test.myFirstDelegate += new MyFirstDelegate(attachedFunction.firstAttachMethod); test.myFirstDelegate += new MyFirstDelegate(attachedFunction.SecondAttachMethod); test.myFirstDelegate += new MyFirstDelegate(attachedFunction.thirdAttachMethod); test.myFirstDelegate += new MyFirstDelegate(attachedFunction.fourthAttachMethod); test.myFirstDelegate += new MyFirstDelegate(attachedFunction.fifthAttachMethod); test.Call(); Console.ReadLine(); } } } 

事件使用Delegates实现。 按惯例说,事件采取以下forms:

  void EventHandler(Object sender, EventArgs args); 

EventHandler实际上是.Net中定义的委托。 EventArgs是.Net中的一个类,它充当占位符以传递其他信息。 如果您有其他信息,您将创建一个派生自EventArgs的类,并包含其他数据的属性; 因此你会像这样创建自己的委托:

 void MyEventHandler(Object sender, MyEventArgs args); 

Microsoft在此处提供了有关事件的教程,并在此处描述了定义和引发事件

这是处理事件的常见模式:

 // define the delegate public delegate void CustomEventHandler(object sender, CustomEventArgs e); // define the event args public class CustomEventArgs : EventArgs { public int SomeValue { get; set; } public CustomEventArgs( int someValue ) { this.SomeValue = someValue; } } // Define the class that is raising events public class SomeClass { // define the event public event CustomEventHandler CustomEvent; // method that raises the event - derived classes can override this protected virtual void OnCustomEvent(CustomEventArgs e) { // do some stuff // ... // fire the event if( CustomEvent != null ) CustomEvent(this, e); } public void SimulateEvent(int someValue) { // raise the event CustomEventArgs args = new CustomEventArgs(someValue); OnCustomEvent(args); } } public class Main { public static void Main() { SomeClass c = new SomeClass(); c.CustomEvent += SomeMethod; c.SimulateEvent(10); // will cause event } public static void SomeMethod(object sender, CustomEventArgs e) { Console.WriteLine(e.SomeValue); } } 

尝试放线

 public delegate void MyFirstDelegate(); 

在Test类中。

另外,请在事件上使用Invoke函数,即

 myFirstDelegate.Invoke();