Negative tive C # item22: Use the event-defined outbound Interface

Source: Internet
Author: User

An event defines an outbound interface for the type. The C # event is based on the delegate, and the delegate provides a type-safe function signature for the event processor.

Delegation is more widely used than events. We can regard events as an encapsulated delegation dedicated to event-driven models. You can directly call the delegate in the client code to stimulate the function to which the delegate points. However, events are not allowed. You can only call the event on the server side, but call the event on the client side will cause a compilation error. Let's look at the following program.

Code

  1     public class EventTest
2 {
3 public delegate int Add(int value1, int value2);
4 public event Add AddHandler;
5 public Add AddDelegate;
6
7 public void OutputAddResult(int value1, int value2)
8 {
9 AddHandler(value1, value2);
10 }
11 }
12
13 public class ClientTest
14 {
15 private EventTest m_EventTest;
16
17 public ClientTest()
18 {
19 m_EventTest = new EventTest();
20 m_EventTest.AddHandler += new EventTest.Add(m_EventTest_AddHandler);
21 m_EventTest.AddDelegate = AddDelegate;
22 //the line below will cause compile error.
23 //m_EventTest.AddHandler(1, 1);
24   m_EventTest.AddDelegate(1, 1);
25 }
26
27 private int m_EventTest_AddHandler(int value1, int value2)
28 {
29 return value1 + value2;
30 }
31
32 private int AddDelegate(int value1, int value2)
33 {
34 return value1 + value2;
35 }
36 }

The code above also indicates that for a delegate, you can not only arrange who calls the function, but also directly call it. For an event, you cannot directly call it, it can only be triggered by some operations.

. Net defines the add and remove accessors for event-type variables. They are similar to get and set in common attributes, we can use "+ =" or "-=" to register or release an event. The add and remove operations are automatically generated by the compiler. When writing code, we should declare a common event and then let the compiler create the add and remove accessors for us.

In the type of the defined event or event, you do not need to know the information of the potential customer caller. That is, the event can only be called on the server and registered on the client for implementation, however, the server does not need to know the client information, and the two are loosely coupled. The server and client mentioned here indicate the types of declared events and registered events respectively.

When there are many types of events, we still define a field for each event, and the change is not desirable. In this case, we can define an event container, dynamically create event objects at runtime. The. NET Framework kernel contains examples of this practice in the Windows Control Subsystem.

We can view the following code and use the container method to save the specific event information.

Code

  1 public class Logger
2 {
3 private static System.ComponentModel.EventHandlerList
4 Handlers = new System.ComponentModel.EventHandlerList();
5
6 static public void AddLogger(
7 string system, AddMessageEventHandler ev )
8 {
9 Handlers[ system ] = ev;
10 }
11
12 static public void RemoveLogger( string system )
13 {
14 Handlers[ system ] = null;
15 }
16
17 static public void AddMsg ( string system,
18 int priority, string msg )
19 {
20 if ( ( system != null ) && ( system.Length > 0 ) )
21 {
22 AddMessageEventHandler l =
23 Handlers[ system ] as AddMessageEventHandler;
24
25 LoggerEventArgs args = new LoggerEventArgs(
26 priority, msg );
27 if ( l != null )
28 l ( null, args );
29
30 // The empty string means receive all messages:
31 l = Handlers[ "" ] as AddMessageEventHandler;
32 if ( l != null )
33 l( null, args );
34 }
35 }
36 }

The above code stores each event processor in the eventhandlerlist set. When the customer code is associated with a specific subsystem (or key value), a new event object will be created. For the same key value, the subsequent request will return the same event object, because the container is a static container. If our type contains a large amount of time in its interface, we should adopt this event easy method. When the customer code is actually associated with the event processor, we will create event members.

 

Summary: events are used to define the type of the outbound interface. Any number of customer objects can register their processor to the event and process them, these customer objects do not need to exist during compilation, and the events do not have to have subscriber to work normally. In C #, events can be used to decouple the sender and possible notification recipients. The sender can be developed independently of the receiver.

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.