Delegates and events

Source: Internet
Author: User

A delegate is an abstraction of one or more function pointers. With a delegate, we can treat the function as data, including using a delegate as a variable, parameter, or data member. It can protect our code and can also be used for callbacks, events and threads ...

A delegate enables a function to be passed as a parameter, can be returned as a value from another function, or even be stored in an array, completely a data. However, they are more secure and reliable than function pointers in C and C + +.

An instance of a delegate encapsulates a function reference and a target object. When a delegate is activated, the delegate invokes the function on the object it encapsulates.

A delegate has a signature (a parameter list) and a return type. The function added to the delegate must be consistent with it.

Definition of delegate (keyword Delegate):

The access modifier delegate returns the type delegate type name (parameter list (signature));

   Public Delegate void MyHandler (string name);

A delegate with a string that returns a type of void is defined.

Take a look at how to use

     Public classFunctionclass { Public voidFunction1 (stringname) {Console.WriteLine ("{0}, Hello", name); }     }///////Use  //MyHandler handler = new MyHandler (new Functionclass (). Function1);MyHandler handler=NewFunctionclass (). Function1;//delegate support implicit instantiationHandler. Invoke ("Ranran");//the excitation delegate is equivalent to handler ("Ranran")

In addition to the Invoke method, there are many other exciting methods, such as the BeginInvoke EndInvoke, which are mainly used for asynchronous delegates, are introduced in another article, and are not discussed here.

Add this here. Two more almighty delegates after net3.5

Func<> delegates and Action<> delegates

Both can be used as a delegate to various signature functions, eliminating the code that defines the delegate, the main difference is that the function of the:func<> delegate has a return type, and the function of the action delegate has no return type!!!

1.func<t1,t2,... Tresult>

2.action<t1,t2...>

See below how to use:

 Public classFunctionclass { Public Static BOOLFunction2 (stringname) {Console.WriteLine ("{0},how do", name); return true; }         Public Static voidFunction3 (stringname) {Console.WriteLine ("{0},how do", name); }         }            ////use:///func-delegate functions have return typesfunc<string,BOOL> Handler2 =Newfunc<string,BOOL>(Functionclass.function2); Handler2. Invoke ("Fan"); ///the function delegate does not have a return typeaction<string> handler3=Newaction<string>(Functionclass.function3); Handler3. Invoke ("Huaran");

Continuation of the commissioning of the explanation:
A delegate is actually not just a function pointer, but a function pointer list. A delegate can delegate n multiple functions, flexible use of +=,-=, which is a queue structure, first-out, first-order first fired, but note that it only returns the return value of the last parameter.

See the following code:

     Public  classHandlerfunc { Public Static voidFun1 () {Console.WriteLine ("T ' m Fun1"); }         Public Static voidFun2 () {Console.WriteLine ("I ' m Fun2"); }         Public Static voidFun3 () {Console.WriteLine ("I ' m Fun3"); }    }/////UseAction Handler4 =handlerfunc.fun1; Handler4+=handlerfunc.fun2; Handler4+=Handlerfunc.fun3; Handler4.invoke ();

Operation Result:

Two knowledge points for final replenishment of the consignment

There are three ways to define and assign a delegate variable

1. Traditional delegation, the above code is

2. Anonymous functions

3.LAMBDA-expression

2 and 3 are very convenient to use, and generally will be used with Func or action, of course, in some places have his shortcomings.

 //Traditional delegation:MyHandler handler =NewFunctionclass ().            Function1; //Anonymous MethodsMyHandler handler2=Delegate(stringname) {Console.WriteLine ("{0}, Hello", name);            }; //Func and action are also available, and the following are anonymous methodsaction<string> handler4 =Delegate(stringname) {Console.WriteLine ("{0}, Hello", name);            }; //using LANBDA expressions (parameters) = = (statement)action<string> handler = (name) and Console.WriteLine ("{0}, Hello", name);

The principle of two-delegate-respecting parameter references is ref and out.

Events

An event refers to a notification.

Events have publishers and Subscribers

A Subscriber is a value notification that generates an event.

The event has a subscriber, and the subscriber registers the event by adding a delegate to the event.

The publisher notifies the Subscriber by invoking the function application of the delegate, and then the Subscriber responds to the event (by means of the code in the function)

The event's keyword is

Syntax for the definition:
Access Modifier event delegate type name Events name;

EventHandler compiler comes with a delegate that handles standard event programs

Storing information about events in EventArgs and its derived classes

See the code below (the NSF event is triggered when the bank account is overdrawn, the Bankeventargs class provides the bank account balance and the transaction amount that causes the account to be overdrawn)

//defines a delegate that stores the event-handling code, and E stores information about the event     Public Delegate voidOverdrawn (ObjectO,bankeventargs e); //class for event information inherits from EventArgs     Public classBankeventargs:eventargs {//about Deposit        Private decimalpropbalance;  Public decimalBalance {Get{returnpropbalance;} }        //about spending        Private decimalproptransaction;  Public decimalTransaction {Get{returnproptransaction;} }        //constructor Function         PublicBankeventargs (decimalAmountbalance,decimalamounttransaction) {             This. propbalance=amountbalance;  This. proptransaction=amounttransaction; }    }     Public classBank {//defining an NSF event         Public Eventoverdrawn NSF; //Define a deposit field        Private decimalPropbalance=0; //define a deposit attribute read-only         Public decimalBalance {Get{returnpropbalance;} }        //Define a deposit function         Public decimalDeposit (decimalamountdeposit) {propbalance+=Amountdeposit; returnpropbalance; }        //define a function that raises an event         Public decimalWithdrwal (Decimal amountwithdraw) {//New deposit = old Deposit-Spend            decimalnewbalance=propbalance-Amountwithdraw; //if deposit is negative raise event            if(newbalance<0)            {                if(nsf!=NULL)                {                    //an object that instantiates an event information deposits the event informationBankeventargs args=NewBankeventargs (Balance,amountwithdraw); //Raising an eventNSF ( This, args); }            }            //Change Deposit Fields            returnPropbalance=newbalance; }    }/////Use      //instantiation ofBank account=NewBank (); //Event SubscriptionAccount. nsf+=Nsfhandler; //DepositAccount. Deposit ( the); //spend 7220 This will raise an eventAccount. Withdrwal (7220);                Console.readkey (); //subscribers ' handling after an event occurs         Public Static voidNsfhandler (ObjectO,bankeventargs e) {Console.WriteLine ("NSF Transaction"); Console.WriteLine ("Balance:"+e.balance); Console.WriteLine ("Transaction:"+e.transaction); }                  

This is the core meaning of the event, although can be implemented through function calls, but the event is more standard, more logical, write events are very necessary!!!!

Delegates and events

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.