zoukankan      html  css  js  c++  java
  • 委托(作用:解耦),lambda的演化

    1.了解委托

      MyDelegate类代码如下:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace MyDelegate
    {
        /// <summary>
        /// 委托可以定义在类外面
        /// </summary>
        public delegate void OutNoReturnNoPara();
        public delegate void OutNoReturnWithPara(int x, int y);
    
        class DelegateClass
        {
            /// <summary>
            /// 1.声明委托,委托的参数与函数的参数必须一致
            /// </summary>
            public delegate void NoReturnNoPara();
            public delegate void NoReturnWithPara(int x, int y);
            public delegate string NoPara();
            public delegate DateTime WithPara(string name,int size);
    
            public static void Show()//静态方法的委托只能调用静态方法
            {
                //2.实例化委托,这里的method实例化后就是一个Plus函数
                NoReturnWithPara method = new NoReturnWithPara(Plus);//等价于NoReturnWithPara method = Plus;
                //3.调用委托
                method.Invoke(3, 4);//等价于method(3, 4);
                method.BeginInvoke(4, 5,null,null);//补充:新建一个线程,异步调用
    
            }
            public static void Plus(int x,int y)
            {
                Console.WriteLine("这里是Plus  x={0}  y={1}", x, y);
            }
        }
    }

      在Program使用DelegateClass.Show();

      可以调用Plus这个方法

    2.委托的用处

      1)打招呼===》普通方法

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace MyDelegate
    {
        class GreetingClass
        {public static void Greeting(string name,PeopleType type)//输入和谁打招呼,和这个人是哪个国家的人
            {
                if(type==PeopleType.Chinese)
                {
                    Console.WriteLine("{0}早上好", name);
                }
                else if(type==PeopleType.English)
                {
                    Console.WriteLine("{0}Morning", name);
                }
                else
                {
                    throw new Exception("wrong PeopleType");
                }
            }
        }public enum PeopleType //枚举,定义国家
        {
            Chinese,English
        }
    }

      在Program使用GreetingClass.Greeting("kxy",PeopleType.Chinese);//kxy是一个中国人,所以使用PeopleType.Chinese

           可以实现给不同国家的人打招呼用对应国家的语言

      但是如果我们需要增加一种语言,则需要修改枚举PeopleType和函数Greeting

      2)打招呼===》委托方法

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace MyDelegate
    {
        class GreetingClass
        {
    
            public static void GreetingChinese(string name)
            {
                Console.WriteLine("{0}早上好", name);
            }
            public static void GreetingEnglish(string name)
            {
                Console.WriteLine("{0}Morning", name);
            }
        }
        public delegate void GreetingHandler(string name);
    }

      Program代码如下:

     GreetingHandler handle = new GreetingHandler(GreetingClass.GreetingEnglish);//指明是哪国人
     handle("flt");//输入人的名字

      当需要增加一种新的语言时,直接增加一个Greeting*******函数就可以了,解除耦合

    3.lambda的演化

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace MyDelegate
    {
        public class Student
        {
            public delegate void NoReturnWithPara(string name, DateTime now);
            /// <summary>
            /// 匿名函数向lambda演化的过程
            /// </summary>
            public static void show()
            {
                //普通委托
                NoReturnWithPara method = new NoReturnWithPara(Study);
    
                //使用匿名函数
                NoReturnWithPara method1 = new NoReturnWithPara(
                    delegate (string name, DateTime now)
                    {
                        Console.WriteLine("{0} {1}在学习", name, now);
                    });
    
                //匿名函数向lambda演化,去掉delegate,加入=>
                NoReturnWithPara method2 = new NoReturnWithPara(
                    (string name, DateTime now)=>
                    {
                        Console.WriteLine("{0} {1}在学习", name, now);
                    });
    
                //匿名函数向lambda演化,去掉类型,因为委托函数会自动标识类型
                NoReturnWithPara method3 = new NoReturnWithPara(
                    (name, now) =>
                    {
                        Console.WriteLine("{0} {1}在学习", name, now);
                    });
    
                //匿名函数向lambda演化,去掉new,这也是最终形式
                NoReturnWithPara method4 = (name, now) => 
                    {
                        Console.WriteLine("{0} {1}在学习", name, now);
                    };
    
                //匿名函数向lambda演化,如果方法体只有一行,可以去掉大括号
                NoReturnWithPara method10 = (name, now) => Console.WriteLine("{0} {1}在学习", name, now);
                method10("zjx",DateTime.Now);
            }
    
            public static void Study(string name, DateTime now)
            {
                Console.WriteLine("{0} {1}在学习",name,now);
            }
        }
    }

    4.其他多种委托使用lambda

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace MyDelegate
    {
        public class Student
        {
            public delegate void NoReturnWithPara(string name, DateTime now);
            public delegate int WithReturnWithPara(int x,int y);
            public delegate string WithReturnNoPara();
            /// <summary>
            /// 委托向lambda演化的过程
            /// </summary>
            public static void show()
            {//没有参数,返回一个string类似,可以省略return和大括号
                WithReturnNoPara meth = () => "我爱学习";
    
                //有两个int参数,返回int类型
                WithReturnWithPara meth2 = (x, y) => x + y;
    
    
                ///////////////////////////在开发中基本不需要自己定义委托,可以使用下面方法/////////////////////////////////
                //Action是一个委托,无返回值  <定义参数类型>
                Action action1 = () => { };//无参数无返回值
                Action<string> action2 = s =>{ };//有参数无返回值,且只有一个参数时可以去掉参数的小括号
                Action<int, string, DateTime> action3 = (x, y, z) => { };//可以有多个参数,自定义
    
                //Func是一个委托,有返回值  <定义参数类型,和返回值类型>
                Func<string> func1 = () => "我爱学习"; //<只有一个类型>,该类型是指返回值类型
                Func<string, int, DateTime> func2 = (x, y) => DateTime.Now;//<参数类型,参数类型,返回值类型>
            }
        }
    }

    5.lambda向linq的扩展

    public static void LinqShow()
            {
                //-----------------------定义一个1到99的数组-------------------------
                List<int> intlist = new List<int>();
                for(int i=1;i<100;i++)
                {
                    intlist.Add(i);
                }
                //-----------------------打印大于55的数字----------------------------
                //-----------------------传统方法-----------------------------------
                foreach(int i in intlist)
                {
                    if(i>55)
                    {
                        Console.WriteLine(i);
                    }
                }
                //-----------------------linq方法-----------------------------------
                var linq = from s in intlist
                           where s > 55
                           select s;
                foreach(int i in linq)
                {
                    Console.WriteLine(i);
                }
                //-----------------------linq方法扩展为lambda------------------------
                foreach (int i in intlist.Where<int>(m => m > 55))
                {
                    Console.WriteLine(i);
                }
                //上面foreach可详写为:
                foreach (int i in intlist.Where<int>(//Where是Linq下的一个Func委托,有返回值
                    (m) => { return m > 55; }//匿名函数,使用lambda表达式
                    )
                    )
                {
                    Console.WriteLine(i);
                }
            }
  • 相关阅读:
    jbpm入门样例
    MinGW 介绍
    Linux守护进程的编程实现
    完毕port(CompletionPort)具体解释
    Linux makefile 教程 很具体,且易懂
    mysql数据文件迁移到新的硬盘分区的方法
    winform正在使用dsoframer迅速&quot;Unable to display the inactive document.Click here to reacitive the document.&quot;
    Android学习路径(七)建立Action Bar
    FreeBSD包管理
    BZOJ 1096 ZJOI2007 仓库建设 边坡优化
  • 原文地址:https://www.cnblogs.com/wskxy/p/9135267.html
Copyright © 2011-2022 走看看