[C #] C # Delegation

Source: Internet
Author: User
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 ");
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.