[ZZ] C # delegation and event explanation in the vernacular series (III)

Source: Internet
Author: User
Tags prototype definition

Source: http://www.cnblogs.com/wudiwushen/archive/2010/04/21/1717378.html

Today I will go on to the above three articles to explain why we encounter so many sender in daily programming activities, the EventArgs e parameter:
Protected void Page_Load (object sender, EventArgs e)
{

}

Protected void btnSearch_Click (object sender, ImageClickEventArgs e)
{

}

Protected void grdBill_RowDataBound (object sender, GridViewRowEventArgs e)
{

}
What do they mean?

Before answering the above questions, we should first understand the encoding specifications of. Net Framework:

1. The name of the delegate type should end with EventHandler.
Ii. Prototype definition of delegation: There is a void returned value and two input parameters are accepted: one Object type and one EventArgs type (or inherited from EventArgs ).
3. The event is named as the remaining part after the EventHandler is removed by the delegate.
4. The types inherited from EventArgs should end with EventArgs.

This is the specification of Microsoft coding. Of course, this is not just a rule, but a rule that gives the program more flexibility. Then we will continue to rebuild the example in the third lecture, let him comply with Microsoft's specifications.

Code

// All Subscriber objects that interest [Subscriber], that is, e, must inherit from Microsoft's EventArgs
// In this example, the subscriber (also called the observer) MrMing and MrZhang are interested in e objects, that is, the magazine [magazine]
Public class PubEventArgs: EventArgs
{
Public readonly string magazineName;
Public PubEventArgs ()
{
 
}
Public PubEventArgs (string magazineName)
{
This. magazineName = magazineName;
}
}

// Publisher (Publiser)
Public class Publisher
{
// Declare a publication delegate
// Here, a parameter sender is added, which represents the Subject, that is, the monitoring object. In this example, It is Publisher.
Public delegate void PublishEventHander (object sender, PubEventArgs e );
// Under the delegated mechanism, we establish a publishing event
Public event PublishEventHander Publish;

// Declare a writable OnPublish Protection Function
Protected virtual void OnPublish (PubEventArgs e)
{
If (Publish! = Null)
{
// Sender = this, that is, Publisher
This. Publish (this, e );
}
}

// The event must be triggered in the Method
Public void issue (string magazineName)
{
OnPublish (new PubEventArgs (magazineName ));
}
}

// Subscriber
Public class MrMing
{
// Events of interest
Public static void Receive (object sender, PubEventArgs e)
{
Console. WriteLine ("Ga ga, I have received the latest issue" + e. magazineName + !! ");
}
}

Public class MrZhang
{
// Events of interest
Public static void Receive (object sender, PubEventArgs e)
{
Console. WriteLine ("Naive, so big, but also watch Naruto, SB James! ");
Console. WriteLine ("my" + e. magazineName + ", wow, haha! ");
}
}

Class Story
{
Public static void Main (string [] args)
{
// Instantiate a publishing house
Publisher publisher = new Publisher ();

Console. Write ("Enter the magazine to be published :");
String name = Console. ReadLine ();

If (name = "Naruto ")
{
// Register a subscriber of interest for this Naruto event. In this example, James
Publisher. Publish + = new Publisher. PublishEventHander (MrMing. Receive );
// The publisher triggers the publishing event of Naruto.
Publisher. issue ("Naruto ");
}
Else
{
// Register a subscriber of interest for this Naruto event. In this example, James [another event registration method]
Publisher. Publish + = MrZhang. Receive;
Publisher. issue ("global daily ");
}
Console. ReadKey ();
}
}

The event that James subscribed to is triggered after I entered Naruto.

Display

Let me explain it again through the example. In fact, we don't need to think too much about Sender and e.

1. the parameter of the Object type in the delegate declaration prototype represents the Subject, that is, the monitoring Object. In this example, It is Publisher (Publisher )..
2. The EventArgs object contains data that the Observer is interested in. In this example, it is a magazine.

Let's take a break and relax the brain. Let's take a look at the famous saying:

A lot of things are like watching a movie. People who watch a movie think they are great, and they may not be doing it!

"The inspiration of the Chinese people is very different from that of the foreign countries. The Inspiration of China is encouraging people to make great volunteers and to become rich and expensive one day. Overseas inspirational encouragement encourages people to face real life and ordinary people's dilemmas. Although the result is rich and expensive, the starting point is different. Relatively speaking, I think the latter is more realistic in operation, the former requires 999 losers to build a success story."

 

Now let's talk about our delegation and events. If you are proficient in the design patterns, they are actually associated with the Observer model, here, I will not describe what the observer mode is. I just want to briefly talk about their association:

In the C # event, the delegate acts as an abstract Observer interface, and the object that provides the event acts as the target object. Delegation is a more loosely coupled design than the abstract Observer interface.

It doesn't matter if you don't understand it. When OO reaches a certain level, you will naturally understand it.

Finally, let's look at one of our most commonly used observer models:

Scenario: When we use a credit card to complete the payment, we will receive text messages or emails, which are actually Observer pattern.

Code

// --- In this example, when the user withdraws the money from the bank account, the user will immediately notify the email and send a text message ---
// The subscriber in this example, that is, the observer is an email or mobile phone.
// The publisher, that is, the Monitored object is a bank account

// Obverser email, the recipient of which the mobile phone is concerned, e: email address, mobile phone number, and withdrawal amount
Public class UserEventArgs: EventArgs
{
Public readonly string emailAddress;
Public readonly string mobilePhone;
Public readonly string amount;
Public UserEventArgs (string emailAddress, string mobilePhone, string amount)
{
This. emailAddress = emailAddress;
This. mobilePhone = mobilePhone;
This. amount = amount;
}
}

// Publisher, that is, the Monitored object-bank account
Class BankAccount
{
// Declare a commission for processing bank transactions
Public delegate void ProcessTranEventHandler (object sender, UserEventArgs e );
// Declare an event
Public event ProcessTranEventHandler ProcessTran;

Protected virtual void OnProcessTran (UserEventArgs e)
{
If (ProcessTran! = Null)
{
ProcessTran (this, e );
}
}

Public void Prcess (UserEventArgs e)
{
OnProcessTran (e );
}
}

// Observer Email
Class Email
{
Public static void SendEmail (object sender, UserEventArgs e)
{
Console. writeLine ("email to user" + e. emailAddress + "Send Email: You are in" + System. dateTime. now. toString () + "the withdrawal amount is" + e. amount );
}
}

// Observer's mobile phone
Class Mobile
{
Public static void SendNotification (object sender, UserEventArgs e)
{
Console. writeLine ("to the user's mobile phone" + e. mobilePhone + "send SMS: You are in" + System. dateTime. now. toString () + "the withdrawal amount is" + e. amount );
}
}

// Subscribe to the system to subscribe to several observers in the banking system to achieve loose coupling with clients
Class SubscribSystem
{
Public SubscribSystem ()
{
 
}

Public SubscribSystem (BankAccount bankAccount, UserEventArgs e)
{
// Now we subscribe to two in the bank account: email and SMS.
BankAccount. ProcessTran + = new BankAccount. ProcessTranEventHandler (Email. SendEmail );
BankAccount. ProcessTran + = new BankAccount. ProcessTranEventHandler (Mobile. SendNotification );
BankAccount. Prcess (e );
}
}

Class Client
{
Public static void Main (string [] args)
{
Console. Write ("Enter the amount you want to withdraw :");
String amount = Console. ReadLine ();
Console. WriteLine ("transaction successful, please take the card. ");
// Initialize e
UserEventArgs user = new UserEventArgs ("jinjiangbo2008@163.com", "18868789776", amount );
// Initialize the subscription system
SubscribSystem subject = new SubscribSystem (new BankAccount (), user );
Console. ReadKey ();
}
}

Console

There is also an observer pattern for hot water heaters on the Internet, which is quite classic. You can check it out.

Next, let's talk about the scenario in which delegate events are used in our daily MES system development. After all, we have learned this technology and we must use it, this is valuable!

Haha! Next, it will be even more exciting!

Related Article

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.