The delegate in C # is implemented by inheriting a class in system. Delegate.
Specific steps:
1. Declare a delegate object. The parameter format must be consistent with the parameter form of the method you want to include.
2. define all the methods you want to define. The parameter format must be the same as that of the delegate object declared in step 1.
3. Create a delegate object and include the desired method in the delegate object.
4. Call the methods contained in the delegate object.
C # code for implementing the delegation mechanism: using system;
// Step 1: declare a delegate object
Public Delegate void mydelegate (string input );
// Step 2: define each method. The parameter format must be the same as that of the delegate object declared in step 1.
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 to the method is {0}", input );
}
}
// Step 3: Create a delegate object and include the preceding Method
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;
}
}
// Step 4: Call the methods contained in the delegate object
Class MyClass3 {
Public void callDelegate (MyDelegate d, string input ){
D (input );
}
}
Class Driver {
Static void Main (string [] args ){
MyClass2 c2 = new MyClass2 ();
MyDelegate d = c2.createDelegate ();
MyClass3 c3 = new MyClass3 ();
C3.callDelegate (d, "Calling the delegate ");
}
}