zoukankan      html  css  js  c++  java
  • 委托

    委托的基本使用:

     class Program
        {
            public delegate void CaculateDel(int x, int y); //用delegate 关键字 定义委托类型CacaluteDel
    
            public static void Add(int x, int y)  //两个方法
            {
                Console.WriteLine(x + y);
            }
            public static void Substract(int x, int y)
            {
                Console.WriteLine(x - y);
            }
    
            static void Main(string[] args)
            {
                CaculateDel myDel = new CaculateDel(Add);  //声明委托CaculateDel类型的变量myDel,并用Add方法初始化
                myDel(100, 200);            //输出300
                myDel += Substract;         //由于委托已经重载了“+”和“-”,因此myDel+=时,可以绑定多个委托
                myDel(1, 2);                //输出3,-1
                myDel -= Add;               //解绑Add方法
                myDel(1, 1);                //输出0
                Console.Read();
            }
        }

    .net framework2.0加入了Action和Func,这使得委托的使用获得精简,可以满足大部分用户需要。

    上例中改为:

       static void Main(string[] args)
            {
                Action<int, int> action = Add;
    
                action(2, 3);
            }

    即可。

    Func则用于有返回值的情况。

    Predicate似乎是更早出现的,其本质相当于Func<T,bool> 。使用方式如:

      Predicate<int> predicate = delegate(int x) { return x % 2 == 0; }; //用一个匿名函数的形式作为表达式
                var b = predicate(2);
                Console.WriteLine(b);
  • 相关阅读:
    post和get区别
    https
    tcp/ip协议
    webpack与gulp的不同
    什么是webpack
    spring boot 输入参数统一校验
    spring boot++jpa+ mysql +maven
    Intellij IDEA 2018.2.2 SpringBoot热启动 (Maven)
    git 从远程仓克隆到本地新分支
    ASP.NET MVC 自动模型验证
  • 原文地址:https://www.cnblogs.com/Benjamin/p/3350330.html
Copyright © 2011-2022 走看看