VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > temp > C#教程 >
  • 匿名委托进阶

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
上面文章介绍了委托、匿名的定义,下面的例子则是由繁入简,废话不多说,直接上代码:<br> class Program
 {
     private   delegate int sum(int x, int y);
     private delegate int MyMulticastDelegate(int x, int y);
     static void Main(string[] args)
     {
       
         Console.WriteLine("委托方式一加法:");
         sum addsum = new sum(add);
         int y = addsum(2, 3);
         Console.WriteLine("委托方式一加法:2+3" + y);
 
        
         
         Console.WriteLine("多波委托:有的时候,我们想要调用一个委托,但同时可以执行多个方法(自定义事件中最为常见),比如,一个工作文档生成之后,系统要将生成文档日志,而且还要被保存到数据库中,对于以上二个操作,如果只想调用一个委托,就可以顺序完成,那么使用多播委托,就可以实现。");
         MyMulticastDelegate sumdele = new MyMulticastDelegate(add);
 
         MyMulticastDelegate subdele = new MyMulticastDelegate(sub);
 
         MyMulticastDelegate multicastDelegate = sumdele+subdele;
 
         multicastDelegate(2,2);
 
 
         Console.WriteLine("委托中的匿名方法(未简化):");
         sum Nofuntion = new sum(delegateint x,int i) { return x * i; });
         int k = Nofuntion(2,3);
         Console.WriteLine(k);
 
         Console.WriteLine("委托中的匿名方法(简化):");
         sum  _sum =(int x, int m)=>{ return x * m; };  
         int z = Nofuntion(2, 3);
         Console.WriteLine(z);
 
         Console.ReadKey();
     }
   
     private static int add(int x, int y)
     {
         Console.WriteLine(x+y);
         return x + y;
     }
     private static int sub(int x, int y)
     {
         Console.WriteLine(x - y);
         return x - y;
     }
     private static void mulitey(int x, int y)
     {
         Console.WriteLine(x * y);
     }
 }
 

 

出处:https://www.cnblogs.com/CarzySunshine/p/13878789.html

 

 


相关教程