The new delegate class is defined as follows:
Public class delegateex { // Declare a delegate Public Delegate void calculatedelegate (int32 X, int32 y ); // Delegate association method 1-implement addition-note that the values of return values and parameters must be the same Public static void add (int32 X, int32 y) { MessageBox. Show ("addition Result:" + (x + y )); } // Delegate association method 2-Subtraction Public static void subtract (int32 X, int32 y) { MessageBox. Show ("subtraction Result:" + (x-y )); } // Delegate association method 3-implement multiplication-copy the above Public static void multiply (int32 X, int32 y) { MessageBox. Show ("Multiplication Result:" + (x * y )); } // Delegate Association Method 4-implement Div Method Public static void divide (int32 X, int32 y) { MessageBox. Show ("division result:" + (x/y )); } } |
The form1.cs class is implemented as follows:
Public partial class form1: Form { Public form1 () { Initializecomponent (); } // Define the delegate Type Variable Private delegateex. calculatedelegate mydelegate; private void button#click (Object sender, eventargs E) {< br> try {< br> // obtain the two elements of the addition. int32 x = convert. toint32 (textbox1.text); int32 y = convert. toint32 (textbox2.text); // mydelegate = new delegateex. calculatedelegate (delegateex. add); mydelegate (x, y); }< br> catch (formatexception Fe) {< BR >} Private void button2_click (Object sender, eventargs E) { Try { // Int x = convert. toint32 (textbox1.text ); Int y = convert. toint32 (textbox2.text ); Mydelegate = new delegateex. calculatedelegate (delegateex. Subtract ); Mydelegate (x, y ); } Catch (system. formatexception Fe) { } } Private void button3_click (Object sender, eventargs E) { Try {// Int x = convert. toint32 (textbox1.text ); Int y = convert. toint32 (textbox2.text ); // How to add Delegation to the delegate chain Mydelegate = new delegateex. calculatedelegate (delegateex. Add ); Mydelegate + = new delegateex. calculatedelegate (delegateex. Subtract ); Mydelegate + = new delegateex. calculatedelegate (delegateex. Multiply ); Mydelegate + = new delegateex. calculatedelegate (delegateex. Divide ); // Use the same method Mydelegate (x, y ); } Catch (formatexception Fe) { } } } |
Explanation: some exceptions may occur when convert type is used in the above process, so I caught it, but I didn't handle it ~