委托,C#本身的委托(Action Func)

1.Action

  分为带泛型的和不带泛型的,带泛型可传入任何类型的参数。

  格式如下: 

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 using System.Windows.Input;
 7 
 8 namespace Demo1
 9 {
10     class Program
11     {
12         static void Main(string[] args)
13         {
14             //泛型委托
15             //Action :
16 
17             //带一个参数的
18             Action<string> ac = DelegateTest;
19             ac("带一个参数");
20 
21             //带两个参数
22             Action<int, int> action = DelegateTest;
23             action(1, 2);
24 
25             Console.ReadKey();
26         }
27 
28         static void DelegateTest(string s)
29         {
30             Console.WriteLine(s);
31         }
32         static void DelegateTest(int a ,int b)
33         {
34             Console.WriteLine(a+b);
35         }
36     }
37 }

  不带泛型,格式如下:
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 using System.Windows.Input;
 7 
 8 namespace Demo1
 9 {
10     class Program
11     {
12         static void Main(string[] args)
13         {
14             // 无参数无返回值的委托
15 
16             Action action1 = DelegateTest;
17             action();
18 
19             Console.ReadKey();
20         }
21 
22         static void DelegateTest()
23         {
24             Console.WriteLine("无参的委托");
25         }
26     }
27 }

2.Func :

    有参数 有返回值的委托 (参数的最后一个为返回值)

 1 Func<int, int, int> objCall = ((a, b) => { return a * b; });
 2             Func<int, int, int> objCall1 = ((a, b) => { return a / b; });
 3             Action<int, int> ob = ((a, b) => { Console.WriteLine(a * b); });
 4             ob(5, 3);
 5 
 6             //----------------------------------------------------//
 7             int result = objCall(5, 3);
 8             int result1 = objCall1(5, 3);
 9             System.Console.WriteLine("结果1为 {0},结果2为{1}", result, result1);
10         
11 
12 
13             // Lambda 表达式   
14             Func<int, bool> dele1 = n => n > 10;
15             // Lambda 语句   
16             Func<int, bool> dele2 = (int n) => { return n > 10; };
17             Console.WriteLine(dele1(16));
18             Console.WriteLine(dele1(8));
19             Console.ReadKey();
原文地址:https://www.cnblogs.com/android-blogs/p/6061504.html