Delegate委托

1. 显式调用

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
    //定义委托
    public delegate int MethodDelegate(int x, int y);
    class Program
    {
        static void Main(string[] args)
        {
            //初始化委托方式一
            //MethodDelegate method = new MethodDelegate(Add);
            //初始化委托方式二
            MethodDelegate method = Add;
            Console.WriteLine(method(10, 20));  //30
            Console.ReadKey();
        }
        private static int Add(int x, int y)
        {
            return x + y;
        }
    }
}
View Code

2. 匿名方法调用

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
    //定义委托
    public delegate int MethodDelegate(int x, int y);
    class Program
    {
        static void Main(string[] args)
        {
            //初始化委托方式一
            //MethodDelegate method = new MethodDelegate(delegate(int x, int y) { return x + y; });
            //初始化委托方式二
            MethodDelegate method = delegate(int x, int y)
            {
                return x + y;
            };
            Console.WriteLine(method(10, 20));  //30
            Console.ReadKey();
        }
    }
}
View Code

3. Lambda表达式调用(相比匿名方法写法更加简单,推荐使用这种方式)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
    //定义委托
    public delegate int MethodDelegate(int x, int y);
    class Program
    {
        static void Main(string[] args)
        {
            //简单的用法
            MethodDelegate method1 = (int x, int y) => { return x + y; };
            MethodDelegate method2 = (x, y) => { return x + y; };
            MethodDelegate method3 = (x, y) => x + y;
            Console.WriteLine(method3(10, 20));  //30

            //复杂的用法
            MethodDelegate method4 = (x, y) =>
            {
                if (x > y)
                {
                    x = x * 10;
                    return x - y;
                }
                else
                {
                    return x + y;
                }
            };
            //调用方式1
            //Console.WriteLine(method4.Invoke(30, 10));//290
            //调用方式2
            Console.WriteLine(method4(30, 10));//290
            Console.ReadKey();
        }
    }
}
View Code
原文地址:https://www.cnblogs.com/LuckyZLi/p/12887532.html