C # Representative Yuan and Event Triggered Representative Yuan is a complicated concept in C #, and the function pointer in the representative element and C / C in C # is very similar to the representative element to encapsulate the reference to the internal method of the representative, and use it to use the representative The method of reference. It has a feature that does not need to know the referenced method belongs to that type object as long as the number of parameters of the function is consistent with the return type.
This is said that it may be more abstract that I will mention a few simple examples. I hope that some basic awareness of the majority of beginners // defines a parameter-free representative of the return value for String Note that this representative element can only reference the object to String. non-parametric method delegate string MyDelegate (); public class MyClass {public string SayHello () {return "Hello the world!";}} public class TestMyClass {public static void Main (string [] args) {MyClass myClass1 = new MyClass (); MyDelegate MyDelegate1 = New MyDelegate (MyClass1.SAYHELLO); // Using MyDelegate1 instead of the object.console.writeline (MyDelegate1 ()); // Output result is Hello The World! And call myclass1. Sayhello (); Effects the same}} If the representative is only this function, it is not too much, and there is a very useful feature representative of the representative of the compound representative of the same type of representative. Can define a compound representative element object - remove a representative element object from a compound representative DELEGATE VOIDEDELEGATE (String S); public class myclass {public void syco (String who) {system.console.writeline (WHO "Hello!" );} public void sayGoodBye (string who) {System.Console.WriteLine (who "good bye!");}} public class TestMyClass {public static void Main (string [] args) {MyClass myClass1 = new MyClass (); MyDelegate mydelegate, mydlegate1; mydlegate = new mydelegate (MyClas) s1.SayHello); myDelegate1 = new MyDelegate (myClass1.SayGoodBye); myDelegate = myDelegate1; // this is equivalent to calling myDeletage myClass1.SayHello called simultaneously and myClass1.SayGoodByemyDelegate ( "love.net"); // execution result output Love.Net Hello!} The event driver is an important feature of the Windows application. The C # representation is used to generate events. Event is used to listen to changes in this component in a component, then give another simple Example // Defines an event agent (Representative element) public delegate void eventHandler (String Str); // Defines the event source class class eventsource {// Definition Representative Yuan as a member of the event source class PUBLIC EVENTHANDLER SAY; public void Triggerevent () {if (this.say! = null) // Because Say is a representative element, the actual operation made by the SAY method is determined by the event handler that is registered to it ("A Event Take Place!");}} // Test Class test {public static void main () {eventsource aeventsource =
New eventsource (); // Registering Event Processing Functions to display a string of characters Similar to this.Click = new eventhandler (Button1_onclick); aeventsource.say = new eventhandler (MyEvent); // So this is the trigger process of demonstration event Automatically trigger // In the graphical interface application, it is generally triggered by the user, and then transmits a message by the operating system and calls the processing function. Therefore, the programmer will only register the event handler // and write the code handler code. the aEventSource.TriggerEvent ();} // event handler public static void MyEvent (string str) {System.Console.WriteLine (str);}} C # event handling mechanism of Analysis Visual: Wang Kaiming event Description: any conducted graphics Programmers developed by user interfaces will know the concept of events. When the user is using the program, the user must interact with the program. For example, when a user clicks on a button on the form, the program generates the button clicked event and responds to the user's operation through the corresponding event handler. This way, the user's intuitive feeling is that the program has implemented the task I have requested. Of course, the event does not necessarily be generated in the case of user interaction, and the inside of the system also generates some events and requests processing, such as clock events is a good example. However, it is necessary to introduce the event handling mechanism in C # (extended to a wider range is the entire .NET framework), we must first understand a concept called "entrusted". C # commissioned: Entrusted, as the name suggestions, the meaning of the middle agents. The commission in the C # allows you to pass on the method in an object to another object that can call the class of the method. You can pass a method M (included in a delegate) in a class A, so that class B can call the method M in class A. At the same time, you can also pass the method in a static manner or in an instance (instance). So this concept is very similar to the concept of a function pointer in the C to call other classes in other classes. The concept of the entrusted first is presented in Visual J , now C # also applies the concept of entrusted, which is also to "brought". " The delegate in C # is implemented by inheriting a class in System.Delegate, below is a specific step: 1. Declare a delegate object, its parameters must be consistent with the parameters of the methods you want to include. 2. Define all the methods you want to define, the parameters of its parameters must be the same as the parameters of the delegate objects declared in the first step. 3. Creating a delegate object and inclusion the desired method is included in the delegate object. 4. The various methods included in it are invoked by the delegate object.
The following C # code shows how to use the four steps to implement the delegation mechanism: use system; file: // Step 1: Declare a delegate object public delegate void mydelegate (String Input); file: // Step 2 :: Define each method, its parameter form and the entrusted objects declared in step 1 must be the same class myclass1 {public void delegateMethod1 (String Input) {Console.Writeline ("this is delegateMethod1 and the input to the method is {0}", Input } PUBLIC VOID DELEGATEMETHOD2 (String Input) {Console.Writeline ("this is delegateMethod2 and the input);}} file: // Step 3: Create a delegate object and will wherein the method comprises class MyClass2 {public MyDelegate createDelegate () {MyClass1 c2 = new MyClass1 (); MyDelegate d1 = new MyDelegate (c2.delegateMethod1); MyDelegate d2 = new MyDelegate (c2.delegateMethod2); MyDelegate d3 = d1 d2; RETURN D3;}} file: // Step 4: Calling the method included by the delegate object class myclass3 {public void calldelegate (mydelegate d, string infut) {d (input);}} Class Driver {static void main (String [] args) {myclass2 (); myclass2 (); mydlegate d = c2.createdelegate (); myclass3 c3 = new myclass3 (); c3.calldelegate (D, "calling the delegate");}}}}}} Function: The event handler in C # is a delegate object with a specific parameter form. The formula is as follows: Public Delegate Void MyEventHandler (Object Sender, MyEventargs E); where the first parameter indicates an object that triggers the event, the second parameter (e) contains some of the event handlers data. The above Myeventargs class is inherited from the Eventargs class, and the latter is some broader class, such as the base class of the MouseEventArgs class, the ListChangeDeventargs class. For GUI-based events, you can use these more widely, the object that has been defined, and you must complete your own class for those who are non-GUI-based events, and will be derived from the Eventargs class. The data to be included is passed to the delegate object.
Here is a simple example: public class myeventargs eventargumentData;} In the event handler, you can reference the delegate object by keyword Event, the method is as follows: public evenet myeventhandler myevent; now, let's create two classes Through these two classes, we can know how C # completed event processing mechanisms work. In our instance, the Class A will provide an event's processing function, and create a delegate object in step 3, which is included in it, and the parameters of the event processing function must be in the parameter form of the delegate object, in step 3 Consistent. The Class A will then pass the delegate object to Class B. When the events in the B class are triggered, the event handler in the A class is called correspondingly.
Here is sample code: use system; file: // Step 1: Declaration Privilege Object PUBLIC DELIC DELIC DELID MyHandler1 (Object Sender, MyEventAndler2); File: // Step 2: Created Method of event processing function Class A {public const string m_id = "class a"; public void onhandler1 (Object sender, myeventargs e) {console.writeline ("I am in onhandler1 and myeventargs is {0}", E.M_ID) Public void OnHandler2 (Object Sender, MyEventargs E) {Console.WriteLine ("I am in OnHandler2 and MyEventArgs IS {0}", E.M_ID);} File: // Step 3: Create a delegate object, and The function contains the object to trigger the event. Public A (b) {MyHandler1 D1 = New MyHandler1 (OnHandler1); MyHandler2 D2 = New MyHandler2 (OnHandler2); B.Event1 = D1; B.Event2 = D2 ;}} File: // Step 4: Call the included method class b {public1; public void fireevent1 (myEventArgs e) {if (Event1! "for public event myHandler2 Event2; Public Void FireEvent1; Public Void FireEvent1; Public Void FireEvent1; = NULL) {Event1 (this, e);}} public void fireevent2 (myEventargs e) {if (Event2! = null) {Event2 (this, e);}}}} public class myeventargs Eventargs}}}}}}} PUBLIC STRING M_ID;} Public String M_ID;} PUBLIC Class Driver {public static void main () {b = New b (); a a = new a (b); myeventargs e1 = new myeventargs (); myeventargs e2 = new myeventargs (); e1.m_id = "Event args for Event 1"; e2.m_id = "Event args for Event 2 "; B.FireEvent1 (E1); B.FireEvent2 (E2);}} Event Processing Function of GUI in C #: Completing Event Processing Functions under GUI and Nothing Distinguished Differences, below We will complete a simple example program through the above way. The primary class MyForm class of this instance program is inherited from the Form class. By observing the entire code and related annotations, you can find that we have not given it a delegate object and reference the delegate object through the Event keyword, that is because the GUI control has long helped us to do this work, its commission The object is System.EventHandler. However, we still have to define methods for each control (that is, the event's handle function) and contains them in the System.EventHandler. In that, when the user and program interacts, the corresponding event handler will be triggered.
Specific code as follows: using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; public class MyForm Form {private Button m_nameButton; private Button m_clearButton; private Label m_nameLabel ; private Container m_components = null; public MyForm () {initializeComponents ();} private void initializeComponents () {m_nameLabel = new Label (); m_nameButton = new Button (); m_clearButton = new Button (); SuspendLayout (); m_nameLabel. Location = new point (16, 16); m_namelabel.text = "Click Name Button, please"; m_namelabel.size = new size (300, 23); m_namebutton.location = new point (16,120); m_namebutton.size = new size (176, 23); m_namebutton.text = "name"; File: // Create a delegate object, including the method, the Click event m_nameButton.Click = new system.eventhandler (namebuttonclicked); m_clearbutton.location = New Point (16,152); m_clearbutton.size = new size (176, 23); m_clearbutton.text = "clear"; file: // Create a delegate object, containing the method and assigns the Click event m_clearbutton.click of the button to the button = new system.eventhandler (ClearButtonClicked); this.clientsize = New Size (292, 271); this.controls.addrange (new control [] {m_namelabel, m_namebutton, m_clearbutton}); this.ResumeLayout (false);} file: // definition method (Event processing function), parameter must be the same in the form of private void NameButtonClicked delegate object (object sender, EventArgs e) {m_nameLabel.Text = "My name is john, please click CLEAR button to clear it";} private void ClearButtonClicked (object sender, EventArgs e) { m_namelabel.text = "Click Name Button, please";} public static void main () {Application.run (new myform ());}} Summary: This, I will initially introduce the event handling mechanism in C #.
Through this article, it is hoped that you have a roughly understanding of the event handling mechanism and even the event handling mechanism in C #, and also hopes that you can clearly "entrust" new concepts. Finally, if you are developing using the integrated development environment with Visual Studio, then each GUI control will automatically generate many of the relevant code, but know that the internal working mechanism is always very large. What is the benefit? C # in the dynamic creation control and event handler
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; namespace Miner {///
this.name = "form1"; this.text = "form1"; this.load = new system.eventhandler (this.form1_load); this.ResumeLayout (false);} #ENDREGION ///
Author: sam1111 in the program design is based on the Windows platform, the event (event) is a very important concept. Because in almost all Windows applications, a large number of asynchronous calls, such as responding to clicking buttons, processing Windows system messages, etc., these asynchronous calls need to be done by events. Even in the next generation development platform --.NET is no exception. So what is an event? The so-called event is a message issued by an object. This message marks a particular behavior that occurs, or a particular condition is established. For example, the user clicks the mouse, there is data arrival on the socket. That trigger (RAISE) event is called an event's sender (Event Sender), capturing and responding to an event of an event called event receiver. Here, we will discuss how our own asynchronous calls are implemented in the mainstream development language C # of .NET. In C #, the implementation of the event relies on Delegate, so we must first understand the concept of delegate. DelegateDelegate is a type in C #, which is actually a class that can hold a reference to a method. Unlike other classes, the Delegate class can have a signature, and it can only hold a reference to the method that matches its signature. Its implementation is very similar to the function pointers in C / C . It allows you to pass a class A method m to the object of another class B, so that the object of class B can call this method M. But than the function pointer, Delegate has many functions that have many function pointers. First, the function pointer can only point to the static function, and DELEGATE can reference the static function and can reference the non-statistial member function. When references the non-static member function, DELEGATE not only saves references to this function portal pointer, but also saves references to class instances that call this function. Second, DELEGATE is an object-oriented object-oriented, type, secure, and reliable control. That is, Runtime ensures that delegate points to an effective way, you don't have to worry that Delegate will point to invalid addend or base address. Implementing a delegate is very simple, you can implement one delegate: 1 by three steps. Declare a Delegate object that should have the same parameters and return value types as you want to pass. 2. Create a Delegate object and incorporate the function you want to pass as a parameter. 3. Call the method by the object to be created in the previous step.
The following is a simple example: use system; public class mydelegatetest {// Step 1, Declare Delegate Object Public Delegate Void MyDelegate (String Name); // This is the way we want to pass, it has the same parameters and return to myDelegate Value Type Public Static Void MyDelegateFunc (String Name) {Console.WriteLine ("Hello, {0}", Name);} PUBLIC Static Void Main () {// Step 2, create a Delegate object MyDelegate MD = New MyDeleGate (MyDelegateTest. MyDelegateFunc); // Step 3, call delegatemd ("SAM1111");}} The output result is: Hello, SAM1111 Learn Delegate, let's take a look, how to handle the event in C #. The event processing in the C # processing event C # is actually a delegate with a special signature, like this: public delegate void MyEventHandler (Object Sender, MyEventArgs E); two of these parameters, Sender representative event senders, e is an event parameter class. MyEventargs class is used to include data related to events, and all event parameter classes must be derived from the System.Eventargs class. Of course, if your event does not include parameters, you can use the System.EventArgs class as a parameter. It is such a simple, combined with Delegate implementation, we can break the implementation of custom events to the following steps: 1. Define the delegate object type, it has two parameters, the first parameter is an event sender object, the second parameter is an event parameter class object. 2. Define event parameter classes, which should be derived from the System.Eventargs class. This step can be omitted if the event does not have a parameter. 3. Defining an event handling method, it should have the same parameter and return value type with the Delegate object. 4. Define an event object with an Event keyword, which is also a delegate object. 5. Add events to the event queue with = operator (- = operator) to delete events from the queue). 6. Write an event trigger method in a way that is required to trigger events. In general, this method should be protected by protected, which cannot be called in public mode, but can be inherited by subclasses. The name is oneventname. 7. Call the event trigger method to trigger the event at the appropriate place.
Here is a simple example: use system; public class eventTest {// Step 1. Define the delegate object Public Delegate Void MyEventHandler (Object Sender, System.EventArgs E); // Step 2 omitted public class myeventcls {// Step 3, Define the event handling method, which has the same parameters and return value class // type public void myeventfunc ("my evenet is ok!");}} // Step 4, define the event object in the event object; {myecls = new myeventcls (); // Step 5, use = operator to add events to the queue in the queue = new myeventhandler (myecls.myeventfunc);} // Step 6, write event trigger function protected void onmyevent (system.eventargs e) {if (myEvent! = null) {if (this, e);} Public void raiseevent () {Eventargs E = New Eventargs (); // Step 7, Trigger Event OnMyevent (E);} public static void main () {EventTest et = new eventtest (); console.write ("please input" A ': "); string s = console.readline (); if (s ==" a ") {et.raiseevent ();} else {console.writeline (" error ");}}} The output is as follows. The black body is user input: please input 'a': Amy Event is OK! Summary Through the above discussion, we generally understand the concept of delegate and Event, and how to use them in C #. I personally think that DELEGATE is a fairly important concept in C #, whimsably uses it, makes some quite complex problems very simple. Sometimes I even think that Delegate can even have a pointer, in addition to can't access physical addresses directly. Moreover, the event is also fully implemented based on delegate. Due to the limited capacity, this article is only a light discussion for Delegate and Event, and I hope that this article can play the role of throwing jade. I really want to have more deep understanding of these two concepts, or recommend everyone to see MSDN. Entrusted and events in C # implement OBServer
I. Introduction to the entrusted 1. Delegation:
In the above, we have mentioned a statement of the delegate type, but there is a stricter provision when declaring for the principal-use type of .NET Framework is declared: (1), the delegation type should be used in two parameters; (2 The two parameters are: indicating the "E" parameter of the "object source" parameter and package event of the event source; (3), the type of "e" parameter should be Eventargs or derived from Eventargs class. . The following definition: Public Delegate Void PrintHandler (Object Sender, System.EventArgs E); then we can declare the entrusted type of event, for example: public event printhandler print; when an event occurs, its client is invoked to provide it. 2. Calling an event: Class declaration After the event, you can process the event as a field indicated by the delegate type. If no customer will be binded to the event, the field will be empty; otherwise the field reference should be invoked when calling the event. Therefore, when you call an event, you will usually check if it is empty, then call the event. (Calling the event, the triggering event can only be performed from within the class that declares the event) {Print (this, e);} 3, event binding: From the outside of the class, the event is A common member of the classic class, through the class name. Event name, but can only make binding and unbinding operations without other operations. Class name. Print = New PrintHandler (Binding method name) // Bind a method to the Class name. Print - = New PrintHandler (Binding method name) // Bind a binding To the print event, the use of the III, the use of the commission and events, the use of the delegate and events in the user interface program, such as the Button and its Click event on the user's UI in WinForm or WebForm: // Set the Button1_Click () method to bind to the Click event of the button control Button1 this.Button1.Click = new System.EventHandler (this Button1_Click.); private void Button1_Click (object sender, System.EventArgs e) // Button1_Click ( Method {...} However, in addition to user interface programs, in many other places also use event-driven mode, such as Observer or Publine / Subscribe: Publish in a class (Publish) A certain event that can be triggered, while other classes can subscribe to the event. Once this publisher triggered the event, then the runtime environment will immediately tell all subscriber classes subscribed to the event: this event happens! Thus each subscriber class can make their own reactions (call the corresponding method).
Let's take a practical example in your life to explain how to use entrustments and events, as well as the benefits of using the entrusted and events: such as a company (scene), you are the boss, there are supervisors and employees in the hand, as a boss you Assignment (entrustment) The competent work of the competent management staff, if an employee plays games, let a supervisor deduct 500 yuan from the employee's salary. This is the commission in reality. In the write program, suppose the programmer is the boss, there are two classes for the supervisors and employees, and the supervisor Xiao Wang and the employee Xiaoshao are two types of object instances. The employee has a method: play the game, and there is an event that plays games. He will inspire this incident in playing games. The supervisor is responsible for handling the event, he is responsible for deducting the salary of the employee of the game 500.
(1) First, let's take a look at a more common design method in the case of non-grazing (of course, this is not the only way, not the best way, but very common): use system; namespace csharpconsole {public Class scenario {[stathread] public static void main (string [] args) {console.writeline ("Scene starts."); // Generate the target instance of the actuator instance Xiao Wang Dao Wang = New supervisor (); // Generator class object instance small sheet, designating his supervisor small Zhang = New employee (Xiao Wang); console.writeline ("The employee has a salary:" small sheet. Salary. Tostring ()); // Employees start playing games. Play games (); console.writeline ("Now the employee remains:" small sheet. Salary .toString ()); Console.writeline ("Scene"); console.readline ();}} // person responsible for dashing money - Director PUBLIC Class () {Console.WriteLine ("Generated Supervisor);
} Public void buckle salary (employee Employee) {Console.writeline ("Dare: good boy, working hours dare to play games"); console.writeline ("Supervisor: See how many salary of your kid"); console.writeline (" Started to buckle salary ... "); system.threading.thread.sleep (1000); Employee. Salary = Employee. Salary - 500; console.writeline (" The buckle is executed. ");}} // If playing games The event public class employee {// save the employee's salary private int m_money; / / Save the employee's supervisor M_Manager; public employee (supervisor Manager) {Console.writeline ("Generate Person Workers."); M_Manager = Manager; // Initializing the employee's supervisor by constructor. M_money = 1000; // Initialize the employee's salary through the constructor. } Public INT salary // This property can operate employee's salary.
{GET {RETURN M_MONEY;} set {m_money = value;}} public void play game () {Console.writeline ("employee starts playing games .."); console.writeline ("employee: cs is fun, hahaha) ! I play ... "); system.threading.thread.sleep (1000); m_manager. THIS);}}}} Problem: The coupling of employee classes and supervisors is too high. It must first create a supervisor class in the customer program. If you do not need a supervisor object, you only need a place to be in place, in order to create The required employee object instance, you have to first create an object instance of a supervisor class; 2. If the scene script (ie, the customer needs) changes (1), now let a new role (a new role Class), such as security, instead of the supervisor, responsible for deducting employee salary when employees playing games, then we have to modify employees, may also need to modify the supervisor; (2) If the scene script increases new demand, request After playing the game, the employee is not only to deduct a salary, but also deduct points in performance, then we have to modify the employee.
(2) Using the implementation of the entrust: There is an example below: Successful operation in the C # console application: use system; namespace csharpconsole {// Definition commission public delegate void PlayGameHandler (Object Sender, System.EventArgs E); // People responsible for deducting money - Director PUBLIC CLASS {PUBLIC Supervisor () {Console.Writeline ("Generated Supervisor");} public void, EventArgs E) {Console.Writeline ("Supervisor: Good Kon, work time, dare to play games "); console.writeline (" Supervisor: See how many salary of your kid "); employee Employee = (employee) sender; console.writeLine (" start buckle salary ... "); system .Threading.thread.sleep (1000); Employee. Salary = Employee. Salary - 500; console.writeline ("The buckle is executed.");}} // If playing games, the event public class employee {// first defines an event, this event means employees playing games.
Public Event PlayGameHandler PlayGame; // Save the variable of employee salary Private Int m_money; public employee () {Console.Writeline ("Generator Workers."); m_money = 1000; // Constructor, initialize employee's salary. } Public INT salary // This property can operate employee's salary.
{GET {RETURN M_MONEY;} set {m_money = value;}} public void play game () {Console.writeline ("employee starts playing games .."); console.writeline ("employee: cs is fun, hahaha) ! I have fun ... "); system.threading.thread.sleep (1000); system.eventargs e = new Eventargs (); onplayGame (e); } Protected Virtual Void onplayGame (Eventargs E) {if (PlayGame! = NULL) {PlayGame (this, e);
}}} Public class scene {[stathread] public static void main (string [] args) {console.writeline ("Scene starts."); // Generate the target instance of the actuate Example Xiao Wang Dao Wang = New supervisor ( ); // Generator class object instance small employee small Zhang = new employee (); // set the delegation, designate monitoring small .playGame = new PlayGameHandler (Xiao Wang. Buckle); console.writeline The employee has a salary: " Xiao Zhang. Salary .toString ()); // Employee start playing game small. Play game (); Console.writeline ("Now the employee remains:" Xiao Zhang. Salary. Tostring ()); console.writeLine ("Scene"); console.readline ();}}} For the previous question: 1 , The inevitable relationship between the competent class and the employee class can be created separately, without the existence of the employee object instance; 2. When the customer program is changed: (1), we only You need to modify the customer program, that is, the Class scene in the above example will be changed to the following: Security Xiao Li = new security (); small .playGame = new PlayGameHandler (Xiao Li. buckle salaries); Responsible for the demand of salary, not to mobilize.