C# 委托与回调

时间:2020-07-23 23:04:14   收藏:0   阅读:86

什么是委托、回调?

  委托是一种方法类型,委托可以把方法的具体实现交给另一个类(委托对象)来管理。在一个类中调用另一个类的方法,此过程叫回调。

委托的应用场景:

  当一个类中需要回调时,用委托解决。

委托案例:

  Person 类中的 GetDownLoad 方法中,要调用 DownLoad 类中的 Down 方法,Down方法中需要打印出是哪个类在调用它。

 1     class Person 
 2     {
 3         public void Down() 
 4         {
 5             DownLoad dl  = new DownLoad();
 6             dl.a = who; // 匿名方法 + Lambda表达式:dl.a = ()=>{ Console.WriteLine("Person"); };
 7             dl.Downl();
 8         }
 9         public void who() 
10         {
11             Console.WriteLine("Person");
12         }
13     }
14     delegate void Name();
15     class DownLoad 
16     {
17         public Name a;
18         public void Downl() 
19         {
20             a();
21             Console.WriteLine("在打印");           
22         }
23     }

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!