usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespacedelegateandevent{ Public classCaculator {//Dim a caculateeventargs,used to save the status info when call the event Public classCaculateeventargs:eventargs { Public ReadOnly intx, y; PublicCaculateeventargs (intXinty) { This. x =x; This. y =y; } } //Dim the event delegate Public Delegate voidCalculateeventhandler (ObjectSender,caculateeventargs e); //Dim the Event Public EventCalculateeventhandler mycalculate; //Support the virtual function//provides a protected virtual method that can be overridden by subclasses to deny monitoring protected Virtual voidOnCalculate (Caculateeventargs e) {if(mycalculate!=NULL) {mycalculate ( This, E); } } //to make a calculation, call the release to indicate that a new calculation has occurred Public voidCalculate (intXinty) {Caculateeventargs e=NewCaculateeventargs (x, y); //Notify all event registrantsOnCalculate (e); } }}
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespacedelegateandevent{/// <summary> ///Dingyuan Event Trigger/// </summary> Public classCaculatormanager { Public voidADD (ObjectSender,caculator.caculateeventargs e) {Console.WriteLine (e.x+e.y); } Public voidSubstract (ObjectSender,caculator.caculateeventargs e) {Console.WriteLine (e.x-e.y); } }}
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespacedelegateandevent{classProgram {Static voidMain (string[] args) {Caculator Calculator=Newcaculator (); //Event TriggerCaculatormanager cm =NewCaculatormanager (); //Event BindingsCalculator. Mycalculate + =cm. ADD; Calculator. Calculate ( -, $); Calculator. Mycalculate+=cm. Substract; Calculator. Calculate ( -, $); //Event LogoffCalculator. Mycalculate-=cm. ADD; Calculator. Calculate ( -, $); Console.read (); } }}
Output:
300
300
-100
-100
Delegates and events