C#语言进阶(一)—委托 第一篇

发布于:2024-06-17 ⋅ 阅读:(18) ⋅ 点赞:(0)

总目录
C# 语法总目录

委托 第一篇

  委托类似于CPP中的函数指针。它定义了一个方法类型,这个方法类型有返回类型和形参,不需要方法体,但是在声明这个方法类型时要添加delegate关键字

1. 基本用法

切换委托的方法指向,从而执行不同方法。

namespace TopSet
{
    internal class Program
    {
        //声明委托类型
        delegate int MethodTypeOfDelegate(int a, int b);
        static void Main(string[] args)
        {
            //给委托类型赋值
            MethodTypeOfDelegate mt = Add;
            Console.WriteLine(mt(1,2));
            mt = Dec;
            Console.WriteLine(mt(2,1));
            Console.ReadLine();
        }

        static int Add(int a,int b)
        {
            return a + b;
        }

        static int Dec(int a,int b)
        {
            return a - b;
        }
    }
}

--输出
3
1

2.委托作为方法参数

委托类型作为某个方法的参数传入

namespace TopSet01
{
    internal class Program
    {
        //声明委托类型
        delegate int MethodTypeOfDelegate(int a);
        static void Main(string[] args)
        {
            int a = 5;
            //传入
            MultiValue(ref a, Add);
            Console.WriteLine(a);
            Console.ReadLine();
        }
		//委托类型作为参数
        static void MultiValue(ref int a,MethodTypeOfDelegate mt)
        {
            a = mt(a);
        }

        static int Add(int a)
        {
            return a * a;
        }
    }
}

3.多播委托

  多播委托就是把需要按照顺序执行的,相同类型的委托方法加到一起,执行的时候会按照顺序执行所有的委托方法。可以用于控制台和日志文件的输出。

下方案例仅供演示用法,具体问题需要灵活变通后使用。

namespace TopSet02
{
    public delegate void MethodTypeOfDelegate(int a);
    public class Util
    {
        public static void PrintSquence(int a,MethodTypeOfDelegate mt)
        {
            mt(a);
        }
    }

    internal class Program
    {
        static void Main(string[] args)
        {
            MethodTypeOfDelegate? mt = null;
			
            //加起来,按照加入的顺序执行
            mt += PrintSelf;
            mt += PrintMul;
            int a = 5;
            Util.PrintSquence(a, mt);

            Console.ReadLine();
        }

        static void PrintSelf(int a)
        {
            Console.WriteLine(a);
        }

        static void PrintMul(int a)
        {
            Console.WriteLine(a*a);
        }
    }
}

--输出
5
25

总目录
C# 语法总目录