【C#】委托,方法回调,匿名函数,拉姆达表达式

① delegate

namespace _01DelegateTest
{

    /* 委托定义调用步骤
     * 1.定义委托类型
     * 2.给委托赋值      
       3.调用委托  */
    //定义一个没有返回值 没有参数的委托(注册的方法应该与委托的形式保持一致,即:无返回值无参数的方法)【签名保持一致】
    public delegate void Dele();
    class Program
    {
        static void Main(string[] args)
        {
            Student s = new Student();
            Dele del = s.Drink;  //可以暂时理解为将 方法存储 delegate委托中 从而通过委托来进行调用
            del += s.Eat;  // 对委托进行注册
            Console.ReadKey();
        }
    }
    public class Student
    {
        public void Drink()
        {
            Console.WriteLine("喝水");
        }

        public void Eat()
        {
            Console.WriteLine("吃饭");
        }
    }
    // 委托 del中相当于存放的是 Drink()方法的地址  调用时,先找到Drink()方法的地址,然后进行调用Drink()方法
}

② 方法回调的初步理解

namespace _02_方法的回调
{
    public  delegate string Dele(string str);
    class Program
    {
        static void Main(string[] args)
        {
            Test(ToUP, "abc"); //方法的回调
            Console.ReadKey();
        }
        public static string Test(Dele del, string str)
        {
            return del(str);
        }

        //方法
        static string ToUP(string str)
        {
            return str.ToUpper();
        }
        static string ToLow(string str)
        {
            return str.ToLower();
        }
    }
}

③ 匿名函数

namespace _03_匿名函数
{
    public delegate int Dele(int num1,int num2);
    class Program
    {
        /*
          匿名函数: delegate(参数){方法体}
             */
        static void Main(string[] args)
        {
            Test(GetMax, 1,2);
            //---->转成匿名函数
            Test(delegate (int a, int b) { return Math.Max(a, b); }, 1, 2);
        }
        static int Test(Dele del,int a,int b)
        {
            return del(a, b);
        }
        static int GetMax(int num1,int num2)
        {
            return Math.Max(num1, num2);
        }
    }
}

④拉姆达表达式

namespace _04_LambdaTest
{
    public delegate void Dele();
    public delegate void Dele1(string name);
    public delegate string Dele2(string name);
    class Program
    {
        static void Main(string[] args)
        {
            Dele del = delegate () { };
            Dele del1 = () => { };

            Dele1 del2 = delegate (string name) { };
            Dele1 del3=(string name)=>{ };
            Dele1 del4 = (name) => { };  //lambda表达式会根据委托的定义自动判断参数的类型

            Dele2 dele5 = (name) => { return name; };
        }
    }
}


版权声明:本文为weixin_45344894原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。