C # Programming Guide (iii) Generic delegation)

Source: Internet
Author: User

Generic delegation is actually a pre-defined Delegate of the. NET Framework, which basically covers all commonly used delegates. Therefore, you do not need to re-declare them.

 

Simple. Let's look at the following simple example:

  1             //void method();
2   Action test1 = () => { Console.WriteLine("void method();"); };
3 //void method(x);
4   Action<int> test2 = (x) => { Console.WriteLine("void method(t1)"); };
5 //void method(x, y);
6   Action<int, int> test3 = (x, y) => { Console.WriteLine("void method(t1, t2)"); };
7
8 test1();
9 test2(1);
10 test3(2, 3);

 

The Action series generic delegation does not return a parameter delegate. I simply cited a non-parameter delegate, with a parameter delegate, and with two parameters delegate. The call is not declared as a normal delegate. The specific method is written by lambda. I have introduced it in the previous article. Isn't it easy? You don't have to write public delegate void VoidDelegate. It is concise and clear.

 

Below are generic delegates with returned values:

  1             //int method();
2   Func<int> test4 = () => 10;
3 //int method(int);
4   Func<int, int> test5 = (x) => x * 2;
5 //int method(int ,int);
6   Func<int, int, int> test6 = (x, y) => x * y;
7
8 Console.WriteLine(test4());
9 Console.WriteLine(test5(3));
10 Console.WriteLine(test6(4, 5));

 

Isn't it easy? The Func series delegate has a return value. But in addition to convenience, I would like to sigh with the help of Microsoft, haha !!

 

Sample Code: Download

 

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.