Event in C #

xiaoxiao2021-03-06  20

/ * Events and abnormalities are similar, they are triggered by the object. However, the difference is that the exception is treated by the TRY Catch block, and the event needs to have the main method of subscribe to its main method (event handler). * And this function must match the requirements of the event, this signature is assigned by a commission. * After the event is triggered by the object, it began to execute its handler.

* /// Next example Using System; Namespace Me {Public Delegate Void AgeHandler (INT X); Public Class Person {Int Age; Public Event AgeHandler AgeAdd; // Define an event PUBLIC PERSON (int X) Num) {agn = Num;} public person (): this (0) {} public int agent {get {return aggra;} set {if (value> agn) // When the set age is older, Trigger event {this.ageadd (value-age); // Parameters transmitted to its age} AGE = value;}}} public class class1 {public static void main (string [] args) {Person P = New Person (20); P.AGEADD = New AgeHandler (p_ageadd); // Add // program for the AgeAdd event of the Person object, is the method p_ageadd p.age = 25; // Trigger event} public static void p_ageadd (int) x) // AgeAdd Event Handle {Console.WriteLine ("Growth" X "Aged");}}} / * Now running the program, will "grow 5 years old" in the console output, but we should find The parameters of many event handlers are as follows: * Private void button1_click (object sender, system.eventargs e) * Because this handler may handle more than one event, sender represents the object that triggered it * e is the parameter transmitted by the event * * Below we write a program * / using system; namespace me {// write a class, the parameter passed for our event PUBLIC CLASS AGEVENTARGS: System.EventArgs {Int Oldage; int newage; public a geEventArgs (int a, int b) {oldage = a; newage = b;} public int OldAge {get {return oldage;}} public int NewAge {get {return newage;}} public int AddAge {get {return newage-oldage }}} // Define a delegate, the second parameter we define the type of PUBLIC DELEGATE VOID AGEHANDLER (Object Sender, Me.AgeEventargs E); Public Class Person {Public String Name; Int Age; Public Event Agehandler AgeAdd; Public Person (int NUM, STRING N) {agn = Num; Name = n;} PUBLIC PERSON (): this (0, "no name") {} public int agent {get {return age;} set {ix (value>

转载请注明原文地址:https://www.9cbs.com/read-44259.html

New Post(0)