• .net委托


    今天要学的是委托

    委托的基本形式

    直接上代码

     1 public delegate int AddDelegate(int x,int y);
     2     class Program
     3     {
     4         static void Main(string[] args)
     5         {
     6             int x=2;int y=5;
     7             AddDelegate addDelegate = new AddDelegate(Add);
     8 
     9 
    10             int result = addDelegate(x, y);
    11             Console.WriteLine("运行结果是:" + result);
    12             Console.ReadLine();
    13         }
    14 
    15         static int Add(int x, int y)
    16         {
    17             return x + y;
    18         }
    19     }


    上面是最原始的委托。但是有人开始说了,我的委托可能只是用一次,还要这么罗嗦的代码,累死人....;还有人会说,实例化委托会有资源消耗,我不想实例化。于是就有了委托的第二种样式和第三种样式

    匿名委托

    去掉了静态函数

     1 public delegate int AddDelegate(int x,int y);
     2     class Program
     3     {
     4         static void Main(string[] args)
     5         {
     6             int x=2;int y=5;
     7 
     8             AddDelegate addDelegate1 = new AddDelegate(  delegate(int a,int b){
     9                 return a + b;
    10             });
    11             int result = addDelegate1(x, y);
    12             Console.WriteLine("运行结果是:" + result);
    13             Console.ReadLine();
    14         } 
    15     }


    或者lamdba的写法

     1 public delegate int AddDelegate(int x,int y);
     2     class Program
     3     {
     4         static void Main(string[] args)
     5         {
     6             int x=2;int y=5;
     7 
     8             AddDelegate addDelegate2 = (int a, int b) =>
     9             {
    10                 return a + b;
    11             };
    12             int result = addDelegate2(x, y);
    13             Console.WriteLine("运行结果是:" + result);
    14             Console.ReadLine();
    15         } 
    16     }


    随着.net版本的演变,出现了Func和Action,它们其实是.net内部封装好的委托,方便大家使用,详细咱这里就不再介绍了。

  • 相关阅读:
    把旧表中数据加入到新表中
    mysql字段-创建时间与更新时间
    springboot-maven依赖源
    刚刚下载的IDEA打不开
    matplotlib-实战01
    实战1-数据清理
    python函数(三)
    交换机配置DHCP中继
    python函数(二)
    用事实说话
  • 原文地址:https://www.cnblogs.com/13579net/p/3389456.html
Copyright © 2020-2023  润新知