Unity C# Basics Review 26 - First Understanding of Delegation (P447)

Delegate Delegate
        in C# corresponds to the pointer in C, but it is different. The pointer in C can point to both a method and a variable, and can perform type conversion. The pointer in
C is actually a memory address variable. It can directly operate the memory,
directly access variables through the memory address, and directly call methods.
        Delegate in C# is strongly typed, which means that it is specified when declaring the delegate
that the variable can only point to methods with specific parameters and return values.
        Using delegate, you can directly create a delegate type with any name. When the system is compiled
, the system will automatically generate this type. You can use delegate void MyDelegate()
to create a delegate class and use ILDASM.exe to observe its members. As can be seen from ILDASM.exe
, it inherits the System.MulticastDelegate class and automatically generates three common methods such as BeginInvoke, EndInvoke, and Invoke.

        The Invoke method is used to call the corresponding method of the delegate object synchronously, while BeginInvoke and EndInvoke are used to call the corresponding method asynchronously.

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

namespace ConsoleApp1
{
    class Skill
    {
        public void Skill1()
        {
            Console.WriteLine("Skill:技能1动画");
        }
        public void Skill2()
        {
            Console.WriteLine("Skill:技能2动画");
        }
        public void Skill3()
        {
            Console.WriteLine("Skill:技能3动画");
        }
        public void Skill4()
        {
            Console.WriteLine("Skill:技能4动画");
        }
        public void Skill5()
        {
            Console.WriteLine("Skill:技能5动画");
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    delegate void AutoSkillPlayer();
    class Program
    {
        static void Main(string[] args)
        {
            AutoSkillPlayer akp = new AutoSkillPlayer(Skill1);
            akp += Skill3;
            akp += Skill4;
            Skill sk = new Skill();
            akp += sk.Skill4;
            akp -= Skill1;
            akp.Invoke();
        }
        public static void Skill1()
        {
            Console.WriteLine("技能1动画");
        }
        public static void Skill2()
        {
            Console.WriteLine("技能2动画");
        }
        public static void Skill3()
        {
            Console.WriteLine("技能3动画");
        }
        public static void Skill4()
        {
            Console.WriteLine("技能4动画");
        }
        public static void Skill5()
        {
            Console.WriteLine("技能5动画");
        }
    }
}

 

Guess you like

Origin blog.csdn.net/weixin_46711336/article/details/125281159