预定义委托(C# and Unity)

C#

自定义委托

cs 复制代码
public delegate int CheckMax(int num1, int num2);

public int Calculate(int num1, int num2)
{
    return num1 >= num2 ? num1 : num2;
}

CheckMax logic = Calculate;
logic(22,24)

Action

1、Action 没有返回值,没有参数

2、Action<T...> 无返回值,可传入多个参数且最多16个

cs 复制代码
//没参数
Action action1;
action1 = SayHello;

public void SayHello()
{
    Console.WriteLine("Hello World!");
}


//有多个参数
Action<int, int, int, int> action2;
action2 = GetSum;

public void GetSum(int num1,int num2,int num3,int num4)
{
    var result = num1 + num2 + num3 + num4;
    Console.WriteLine(result);
}

Func

Func <T...> 支持参数1~17个参数,且只有一个返回值在尖括号的最后一个参数

cs 复制代码
Func<int,int,bool> func;
func = IsOver;
func(50, 60);

public bool IsOver(int num1,int num2)
{
    return num1 + num2 >= 100;
}

Predicate

Predicate有且只有一个参数和一个返回值,且返回值只能为bool

cs 复制代码
Predicate<int> predicateTest;
predicateTest = IsGood;

public bool IsGood(int score)
{
    return score >= 80;
}

Unity

UnityAction

Unity自带预定义委托,没有返回值,方法参数的个数支持0~4个。

cs 复制代码
UnityAction<string,string> unityAction;
unityAction = SayHello;
unityAction("小明", "小红");

public void SayHello(string name1,string name2)
{
    Console.WriteLine($" {name1}和{name2},Hello World!");
}
相关推荐
bugcome_com11 小时前
零基础入门C#:一篇搞懂核心知识点
c#
小李也疯狂12 小时前
Unity 中的立方体贴图(Cubemaps)
unity·游戏引擎·贴图·cubemap
牛掰是怎么形成的12 小时前
Unity材质贴图引用陷阱:包体暴涨真相
unity·材质·贴图
呆呆敲代码的小Y12 小时前
【Unity工具篇】| 超实用工具LuBan,快速上手使用
游戏·unity·游戏引擎·unity插件·luban·免费游戏·游戏配置表
EQ-雪梨蛋花汤12 小时前
【Unity优化】Unity多场景加载优化与资源释放完整指南:解决Additive加载卡顿、预热、卸载与内存释放问题
unity·游戏引擎
我的offer在哪里13 小时前
用 Unity 从 0 做一个「可以玩的」游戏,需要哪些步骤和流程
游戏·unity·游戏引擎
泡泡茶壶ᐇ13 小时前
Unity游戏开发入门指南:从零开始理解游戏引擎核心概念
unity·游戏引擎
程序员敲代码吗14 小时前
如何通过命令行启动COMSOL的参数化、批处理和集群扫描
java·c#·bash
YigAin15 小时前
Unity中的Lock,到底在锁什么,什么时候该用?
unity
Var_al15 小时前
抖小Unity WebGL分包命令行工具实践指南
unity·游戏引擎·webgl