About the event and some contrast to the commission

xiaoxiao2021-03-20  215

Using system;

Namespace ConsoleApplication3

{

Public delegate void mydelegate (String Str);

Class class1

{

Private static void Hello (String Str) {

Console.writeLine ("Hello" Str);

}

Private static void goodbye (string str) {

Console.writeLine ("Goodbye" Str);

}

Static void main (string [] args)

{

MyDelegate A, B, C, D;

a = new mydelegate (hello);

B = new mydelegate (goodbye);

C = a b;

D = C - a;

A ("a");

b ("b");

C ("c");

D ("d");

Console.readline ();

}

}

}

My understanding is that delegate is a function of a function, which is essentially a function, which requires the return value and parameter list of the function when binding, must meet the requirements of Delegate declaration.

At this time, I will compare Event.

This.Load = New System.EventHandler (this.page_load);

Obviously, this.Load is an event and a delegate, and the system.eventhandler () is also a delegate, and his return value is the same as the parameter list and this.load. At this time, Page_Load is a specific function bound by System.EventHandler, which is the same as the return value and parameter list of the top. When this.Load event happens, triggered the new NEW SYSTEM.EVENTHANDLER, thereby running Page_Load.

Found an example, event handling

Using system;

Public Class Eventtest

{

Public Delegate Void MyEventHandler (Object Sender, System.EventArgs E);

Public Static Void MyEventFunc (Object Sender, System.EventArgs E)

{

Console.writeline ("My Event IS DONE!");

}

PRIVATE EVENT MyEventHandler MyEvent;

Public EVENTTEST ()

{

This.Myevent = new myeventhandler (myEventfunc);

}

Public void raiseevent ()

{

Eventargs e = new eventargs ();

IF (MyEvent! = NULL)

MyEvent (this, e);

}

Public static void main ()

{

Eventtest et = new eventtest ();

Console.writeline ("Please Input A");

IF (console.readline () == "a")

et.raiseevent ();

Else

Console.writeline ("Error");

}

}

// Herevent here is an event and a delegate, which gives him a process of delegate, which is an eventHandler, which is added to this event. Inside the constructor, the MyEventFunc and Handler are bound. So, if the event is triggered, the binding function is "published on 2005-03-03 10:47 AM

Event is DELEGATE, but it is only the reduction of Delegate, or a restricted version. . . . Event removes the direct assignment of Delegate, others like Delegate.

That is to say that Event is a delegate that cannot use = operator.

转载请注明原文地址:https://www.9cbs.com/read-130382.html

New Post(0)