zoukankan      html  css  js  c++  java
  • .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内部封装好的委托,方便大家使用,详细咱这里就不再介绍了。

  • 相关阅读:
    配合网页滚屏播放,做解说词
    @enable跟@import注解
    组合注解与元注解
    Spring Aware
    https的设计原理
    用信鸽来解释 HTTPS
    http三次握手四次挥手
    一致性哈希
    redis cluster原理
    redis cluster集群搭建
  • 原文地址:https://www.cnblogs.com/13579net/p/3389456.html
Copyright © 2011-2022 走看看