zoukankan      html  css  js  c++  java
  • 多播委托和匿名方法再加上Lambda表达式

      多播委托就是好几个方法全都委托给一个委托变量

      代码:

     1 namespace 委托
     2 {
     3     class Program
     4     {
     5         static void math1()
     6         {
     7             Console.WriteLine("这是第一个方法");
     8         }
     9 
    10         static void math2()
    11         {
    12             Console.WriteLine("这是第二个方法");
    13         }
    14 
    15         static void Main(string[] args)
    16         {
    17         
    18             //多播委托
    19             Action vae = math1;
    20             vae += math2;
    21             Delegate [] deleg = vae.GetInvocationList();  //把vae这个委托里面的方法全部给一个委托数组
    22             foreach (Delegate item in deleg)
    23             {
    24                 item.DynamicInvoke();     //通过遍历语句,把这些方法再一个个的实现
    25             }
    26 
    27             Console.ReadKey();
    28         }
    29     }
    30 
    31 }

      匿名方法本质上还是一个方法,只是它没有名字,任何使用委托变量的地方都可以使用匿名方法赋值

      代码:

      

     1 namespace 委托
     2 {
     3     class Program
     4     { 
     5             //匿名方法,委托方法体结束需要加分号
     6    
     7             Func<int, int> vae = delegate(int i)   //这是Func
     8             {
     9                 return i;
    10             };
    11             Console.WriteLine(vae(5));
    12 
    13 
    14             Action a = delegate()                 //这是Action
    15             {
    16                 Console.WriteLine("哈哈哈哈哈哈");
    17             };
    18             a();
    19   
    20 
    21             Console.ReadKey();
    22         }
    23     }
    24 
    25 }

      Lambda表达式,作用就是为了简化匿名方法

      代码: 

     1 namespace Lambda表达式
     2 {
     3     class Program
     4     {
     5         static void Main(string[] args)
     6         {
     7             Func<int, int, int> dele = (lg1, lg2) =>  //=>这个符号是规范是必须写的,lambda表达式就是为了简化委托的匿名方法
     8             {
     9                 return lg1 + lg2;
    10             };
    11 
    12             Console.WriteLine(dele(8,5));
    13 
    14             Func<int, int> dele = a => a+1;
    15             Console.WriteLine(dele(5));
    16             Console.ReadKey();
    17         }
    18     }
    19 }
  • 相关阅读:
    PHP面试题遇到的几个坑。...面壁ing
    Java基础- super 和 this 解析
    openStack use
    ceph伦理概念
    openstack core components use 总结
    current imporant Posts
    openNebula rgister img instance vms error collections
    openStack images概念及维护
    Error copying image in the datastore: Not allowed to copy image file
    OpenNebula openldap集成
  • 原文地址:https://www.cnblogs.com/yunquan/p/4927385.html
Copyright © 2011-2022 走看看