Use of Unity3D delegate


Function callback mechanism - delegation

using UnityEngine;
using System.Collections;

public class DelegateScripts:MonoBehaviour
{
   //声明一个委托类型,它的实例引用一个方法
   internal delegate void MyDelegate(int num);
   MyDelegate myDelegate;

   void Start()
   {
       //委托类型 MyDelegate的实例myDelegate引用的方法是
       //PrintNum
       myDelegate=PrintNum;
       myDelegate(50);
       //委托类型 MyDelegate的实例myDelegate引用的方法是
       //DoubleNum
       myDelegate=DoubleNum;
       myDelegate(50);

   }

   void PrintNum(int num)
   {
       Debug.Log("Print Num: "+num);

   }
   void DoubleNum(int num)
   {
        Debug.Log("Double Num:"+num*2);
   }
}

At the beginning, you can't see the declaration of the internal delegate type MyDelegate. The delegate needs to determine a callback method signature, including parameters and return types. In this example, the parameter type of the callback method of MyDelegate is int, and the return type is void. In the sentence "myDelegate=PrintNum;", the method group conversion provided by C#2 for the delegate is used. When using method group conversions, an implicit conversion converts a method group to an arbitrary delegate type with a compatible signature. The code demonstration is as follows:

public class DelegateScript:MonoBehaviour
{
    //声明一个委托类型,它的实例引用一个方法
    delegate void MyDelegate(int num);
    //声明一个委托类型,它的实例引用一个方法
    delegate void Mydelegate2(int num1, int num2);

    MyDelegate myDelegate;
    Mydelegate2 myDelegate2;

    void Start()
    {
        myDelegate = PrintNum;
        myDelegate(50);

        myDelegate2 = PrintNum;//重载版本
        myDelegate2(50,50);
    }

    void PrintNum(int num)
    {
        Debug.Log("Print Num:" + num);
    }
    void PrintNum(int num1,int num2)
    {
        int result = num1 + num2;
        Debug.Log("result num is:" + result);
    }
}

Covariance and contravariance of delegation
Covariance means that the return type of the method can be derived from the return type of the delegate , that is to say, the covariance describes the return type of the delegate. Reversibility means that the type of the parameter obtained by the method can be the base class of the type of the delegated parameter . In other words, reversibility describes the type of the delegated parameter. An example is as follows:
we have the base unit class BaseUnitClass, soldier class SoldierClass, and hero class HeroClass in our project. The soldier class and the hero class are derived from the base unit class. Then you can
define a delegate and the code is as follows:

delegate Object TellMeYourName(SoldierClass Soldier);//定义一个委托
TellMeYourName tell;//委托实例 
string TellMeYourNameMethod(BaseUnitClass base);//构造一个该委托类型的实例来引用具有这个原型的方法
tell=TellMeYourNameMethod;

In this example, the parameter type of the TellMeYourNameMethod method is BaseUnitClass, which is the base class of the parameter type SoldierClass delegated by TellMeYourName, and the contravariance of this parameter is allowed. The return value type of the TellMeYourNameMethod method is string, which is derived from the return value type Object of the TellMeYourName delegate, so the covariance of this return value type is also allowed. But one thing to point out is that covariance and contravariance only support reference types, so if it is a value type or void, it does not support it.

Simplified syntax for delegates


Anonymous methods
Usually when using a delegate, it is often necessary to declare the corresponding method, for example, the parameter and return value types must conform to the method prototype determined by the delegate type. Moreover, in the actual game development process, it is often necessary to delegate this mechanism to handle very simple logic, but correspondingly, a new method must be created to match the delegate type, which will make the code look very bloated. Therefore, in the C#2 version, the mechanism of anonymous methods was introduced. For example:

Action<string> tellMeYourName = delegate (string name)
{
       string intro = "My name is";
       Debug.Log(intro+name);
};

This code uses the "anonymous method" mechanism. The so-called anonymity means that the method does not have its own name, but assigns the method in {} to the delegate instance tellMeYourName at the beginning. After that, we can call tellMeYourName directly. For example

tellMeYourName(“ssw”);//这样便会输出 My name is ssw

Two common delegation generics are: Action<T> and Func<T>. Among them, Action<T> has no return value, and Func<T> has a return value. Their manifestations are as follows:

public delegate void Action();
public delegate void Action<T1>(T1 arg1);
public delegate void Action<T1,T2>(T1 arg1,T2 arg2);//...还有很多
public delegate TResult Func<TResult>();
public delegate TResult Func<T1,TResult>(T1 arg1);
public delegate TResult Func<T1,T2,TResult>(T1 arg1,T2 arg2);//...还有很多

In addition, there are some C# preset delegate types that may be encountered in the actual development process, such as the delegate type Predicate<T> whose return value is bool. Its signature is as follows:

public delegate bool Predicate<T>(T obj);

Predicate<T> often comes into play when filtering and matching objects.
Returns a delegate type Comparison<T> whose value is int. Its signature is as follows

public delegate int Comparison<in T>(T x,T y)


About the Generic Modifier in (Generic Modifier) ​​- C# Reference | Microsoft Learn

————————————————
Original link: https://blog.csdn.net/ssw940521/article/details/78446451

Supongo que te gusta

Origin blog.csdn.net/weixin_42565127/article/details/132204740
Recomendado
Clasificación