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