c#中的委托

 使用场景
当要给方法传递另一个方法时,需要使用委托,即将方法作为方法的参数。
有两句很经典的话在此引用,加深理解:1.你不知道怎么做(一般结果知道,但实现细节不知道)那么请委托给别人做
2.你什么都知道,但是你没权限做(或你的职责里没有这项权利)那么请委托给有权限的做个事情的人做
 
优点
编写程序的时候要调用某个方法,但是不知道调用是哪个方法,若使用委托只要传递参数,取返回值就行。使用委托操作函数就像操作变量一样,因此更加灵活
 
声明
delegate 返回值类型 委托类型名(参数)。
 
:声明的委托是一种类型,实际要使用时还要声明委托类型的变量,如 SomeDelegate sd1;
 
和直接调用函数的区别
用委托就可以指向任意的函数,哪怕是之前没定义的都可以,而不使用受限于那几种。
 
使用例子1:
class Program
    {
        static void Main(string[] args)
        {
            SomeDelegate sd1 = new SomeDelegate(Some1);//将委托类型变量指向函数 注:委托可以看做是函数的指针
//SomeDelegate sd1 = Some1;//可以简化成这样 编译器帮我们进行了new sd1("sd1", 3); SomeDelegate sd2 = Some2; int i = sd2("sd2", 4); Console.WriteLine(i); Console.ReadKey(); } static int Some1(string s1, int i1) { Console.WriteLine("some1"); return i1; } static int Some2(string s2, int i2) { Console.WriteLine("some2"); return i2; } } delegate int SomeDelegate(string s,int i);//声明一个委托
例子2:根据用户输入1转大写,2转小写
 
 1 class Program
 2 
 3     {
 4 
 5         static void Main(string[] args)
 6 
 7         {
 8 
 9             string str = "I Will Be A Strong Man";
10 
11             string inputStr = Console.ReadLine();
12 
13             BigSmallConvertDelegate d = null;
14 
15             if (inputStr == "1")
16 
17             {
18 
19                 d = ConvertToBig;
20 
21             }
22 
23             else if (inputStr == "2")
24 
25             {
26 
27                 d = ConvertToSmall;
28 
29             }
30 
31             str = d(str);
32 
33             Console.WriteLine(str);
34 
35             Console.ReadKey();
36 
37         }
38 
39         static string ConvertToBig(string str)
40 
41         {
42 
43             return str.ToUpper();
44 
45         }
46 
47         static string ConvertToSmall(string str)
48 
49         {
50 
51             return str.ToLower();
52 
53         }
54 
55     }
56 
57     delegate string BigSmallConvertDelegate(string str);
View Code

例子3:写一个函数,接受1个委托对象参数和一个string数组,函数内部使用数组每个元素为参数调用委托对象

 1 class Program
 2     {
 3         static void Main(string[] args)
 4         {
 5             int[] arr = new int[] { 2,3,4,5,6};
 6             ProcessInt(arr,AddOne);
 7             Console.ReadKey();
 8         }
 9         static int AddOne(int num)
10         {
11             return num + 1;
12         }
13         static void ProcessInt(int[] nums, ProcessIntDelegate pi)
14         {
15             for (int i = 0; i < nums.Length; i++)
16             {
17                 nums[i] = pi(nums[i]);
18                 Console.WriteLine(nums[i]);
19             }
20         }
21       
22     }
23     delegate int ProcessIntDelegate(int num);
View Code
委托组合
将多个方法绑定到同一个委托,当调用该委托时,依次调用其绑定的方法。
语法:如HelloWordDelegate hwD=Fun1;hwd+=Fun2;第一次用的“=”,是赋值的语法;第二次,用的是“+=”,是绑定的语法。-=就是取消对方法的绑定
注:组合的委托必须是同一个类型,委托组合一般用于事件。
 
 
  • 一步一个脚印,稳扎稳打,实事求是。
  • 记录所学知识,记录自己的成长轨迹。
  • 记录过程中,发现问题并解决问题。
  • 感谢您的阅读!(●'◡'●),如果您觉得本文对您有帮助的话,麻烦点个推荐,欢迎转载,转载请带上原文链接,谢谢!
原文地址:https://www.cnblogs.com/kungge/p/4676442.html