初始delegate委托

刚刚接触c#不足三个月,最近网上查了一下c#的delegate委托。发现delegate更类似于之前学习c语言时候的指针,可以调用其它方法。

使用委托可以将方法作为参数来赋值和传递。

 1     //定义委托
 2     public delegate void MyTestDelegate(int i);
 3     class Program
 4     {
 5         static void Main(string[] args)
 6         {
 7             //创建delegate类型,同时调用DelegateFunction方法
 8             ReceiveDelegateArgsFunc(new MyTestDelegate(Program.DelegateFunction));
 9         }
10 
11         //这个方法接收一个delegate类型的参数,也就是接收一个函数作为参数
12         public static void ReceiveDelegateArgsFunc(MyTestDelegate myTest)
13         {
14             myTest(123);
15         }
16         // 想要传递的方法,需要和MyTestDelegate具有相同的参数和返回值类型
17         public static void DelegateFunction(int i)
18         {
19             Console.WriteLine("参数为:" + i);
20             Console.ReadLine();
21         }
22     }
原文地址:https://www.cnblogs.com/tearfc/p/5343993.html