Delegate (delegates) and event (events) in C #

Source: Internet
Author: User

Delegate: entrusted to others to do this, including entrust themselves, that is, a method can call the other methods of no relationship, you can also pass the delegate past, callback their own methods, and can be customized parameters, very convenient to each other value, suitable for decoupling relationship.

Example:

public delegate void Changemoney (object s, int n); Declaring a delegate with delegate

1. Call Other methods

The sale page adds the item, and the added item can be seen on another page.

Sell Page class inside define delegate:

Define a delegate
public delegate void Getproducthander (list<markingmodel> mlist);
Associating a created delegate with a specific event
public static event Getproducthander GetProduct;

Call the delegate method when you click Add Item:

If (click Add Item)

{

GetProduct. Invoke (_list);

}

Another page invokes the delegate:

Productsalemarketing.getproduct + = new Productsalemarketing.getproducthander (GetList);

The GetList method to be called is placed behind the getproduct (from inside the class). and implementing the GetList method

private void GetList (list<markingmodel> _mlist)
{

}

2. Equivalent callback method

This defines the delegate outside the class, because the callback is a method that instantiates the delegate on another page and invokes the connection. Who is calling behind behind.

public delegate void Changemoney (object s, int n); Declaring a delegate outside the page can be called by another page

public partial class Tihuobill:baseform
{

Multi-Window Common events
private void Sn_evedelselectnumber (object cash, int n)
{
Changepay (cash, n);
}


Cash
private void Btncash_click (object sender, EventArgs e)
{
var sn = new Shownumber (7);
sn. Cardmoney = _daishou;
sn.  Evedelselectnumber + = Sn_evedelselectnumber; This is the main sentence. The delegate is instantiated on the Shownumber page, and + = is called after the page executes Sn_evedelselectnumber
sn. ShowDialog ();
}

}

Shownumber page:

Public Changemoney Evedelselectnumber; Instantiating a delegate

Determine when the page is closed

private void Btnsure_click (object sender, EventArgs e)
{

Evedelselectnumber (Selectmoney, SelectType); Call the delegate and pass the value or this way: Evedelselectnumber.invoke (Selectmoney, SelectType);

}

Temporarily discover that delegates can use both of these methods

where delegate and event effects are the same

Difference: The difference between event and delegate
First, by adding the event keyword, the compiler automatically generates a private field for the event (the delegate associated with the event), and two accessor methods, the add accessor method and the remove accessor method, for registering and Unregistering events (using + = and-= for events). Operation is called both methods).
I think your problem is basically that a field that declares a delegate type can also implement these functions.
In fact, the use of event rather than the direct use of the delegate, in fact, for encapsulation. As you can imagine, if you take a public delegate field directly, you can manipulate the field directly from outside the type, such as by assigning it directly to NULL.
Using the Event keyword guarantees that the operation of the events is limited to the add accessor method and the Remove accessor method (that is, only + = and-= are used)

In MSDN, a paragraph describing the relationship between delegate and event is simple:

Declaring an event: to declare an event within a class, you must first declare the delegate type of the event.

The delegate also applies to the Observer pattern:

    Class Program {Staticvoid Main (String[] args) {var car =New Car (15);New Alerter (CAR); Car. Run (120); } }Class Car {PublicDelegatevoid Notify (IntValue);PublicEvent Notify Notifier;Privateint petrol = 0;Publicint Petrol {get {return petrol; } set {petrol =Valueif (Petrol < 10)//When the value of petrol is less than 10 o'clock, departure alert {if (notifier! =NULL) {notifier. Invoke (Petrol); } } } }public Car (int petrol) {petrol = petrol;} public void Run (int speed) {int Distance = 0; while (Petrol > 0) {thread.sleep (500); petrol--; Distance + = speed; Console.WriteLine ( "Car is running ... Distance is "+ Distance. ToString ()); }}} class Alerter {public Alerter (car car) {car.notifier + = n EW car.notify (Notenoughpetrol); } public void Notenoughpetrol (int  Value) {console.foregroundcolor = consolecolor.red; Console.WriteLine ( "You are only having" + value. ToString () +  "gallon petrol left!"); Console.resetcolor (); } } 

After reading the above code, you might ask: Why not call Alerter.notenoughpetrol directly in public int petrol? Because the car module and the Alerter module itself are two separate subsystems, if called directly, the coupling will increase, which is not what we would like to see.

In fact, the above code is the implementation of the Observer pattern in the design pattern (Observer mode, also known as the Source/listener mode), when the car is running in the <10 of gasoline, the alarm will be issued alarm. In the above code, delegate is equivalent to a function pointer that holds the callback function, and with delegate, we can implement the observer pattern very conveniently. In fact, we can consider using delegate when we need to use a callback function.

I wonder if you have noticed that there is a problem in the code above?

Event Notify Notifier;

In the above code, we define an event, and in fact:

Public Notify notifier;

This writing, also fully satisfies our needs, which leads us to another problem, delegate and event! As described above.

Reference: Talking about the delegate in C #

The difference between event and delegate

Finally, the delegate (delegate) and event (events) in C # are used.

Delegate (delegates) and event (events) in C #

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.