Action与Func是.NEt中的内置委托类型,可以直接用来定义委托而无需先声明,非常的方便
Action的简单运用
//使用Action,Func等.Net自带的内置委托Action和Func
//须引用名称为System的命名空间
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/*//无参
public delegate void Action();
//1个参数
public delegate void Action<in T>(T obj);
//2个参数
public delegate void Action<in T1, in T2>(T1 Obj1, T2 obj2);*/
public class ActionTest : MonoBehaviour
{
//无参
Action SayGoodBayAction;
//一个参数
Action<string> SayHelloAction;
//两个参数
Action<string, string> strTestAction;
// Start is called before the first frame update
void Start()
{
SayHelloClass mySayHello = new SayHelloClass();
mySayHello.OnHello("Tom1");
SayHelloAction = myTest;
SayHelloAction += myTest;
SayHelloAction += mySayHello.OnHello;
SayGoodBayAction = myTest2;
strTestAction = myTest3;
SayHelloAction.Invoke("Tom");
SayGoodBayAction.Invoke();
strTestAction.Invoke("汤姆" , "杰瑞");
}
// Update is called once per frame
void Update()
{
}
private static void myTest( string name)
{
Debug.Log($"This is a Test,{name}");
}
private static void myTest2()
{
Debug.Log("This is myTest2");
}
private static void myTest3(string str1, string str2)
{
Debug.Log($"{str1} + {str2}");
}
}
public class SayHelloClass : ISayHello
{
public void OnHello(string message)
{
Debug.Log($"Hello,my name is {message}");
}
}
public interface ISayHello
{
void OnHello(string message);
}
Func的简单运用
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Func : MonoBehaviour
{
Func<int,int,int> myFunc = null;
// Start is called before the first frame update
void Start()
{
myFunc = Add;
if(myFunc != null)
{
int result = myFunc.Invoke(2, 3);
Debug.Log(result);
}
myFunc -= Add;
//检查是否有误
try
{
myFunc.Invoke(5, 2);
}
catch
{
Debug.Log("委托可能为空");
}
finally
{
//重新指向Add函数
myFunc = Add;
Debug.Log($"result = {myFunc.Invoke(10,8)}");
//移出Add
myFunc -= Add;
//Lambda表达式
//指向匿名函数
myFunc = (x, y) =>
{
return x + y;
};
Debug.Log($"result = {myFunc.Invoke(9, 6)}");
}
}
// Update is called once per frame
void Update()
{
}
//加法
int Add(int x, int y)
{
int z = x + y;
return z;
}
//减法
int Mul(int x, int y)
{
int z = x - y;
return z;
}
}