预定义委托(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!");
}
相关推荐
hez20103 天前
在 .NET 上构建超大托管数组
c#·.net·.net core·gc·clr
雨落倾城夏未凉8 天前
第四章c#方法-参数数组和可选参数(16)
后端·c#
唐青枫9 天前
线程不是越多越快:C#.NET Thread 生命周期、同步与后台工作线程实战
c#·.net
唐青枫10 天前
别只会反射:C#.NET Emit 动态生成代码实战详解
c#·.net
咕白m62510 天前
.NET 环境下 Word 超链接批量提取方案
c#·.net
用户917215619021110 天前
C# 通信协议增量解析:用状态机处理半包和粘包
c#
小码编匠11 天前
C# 工控上位机必备:数据转换工具类与十个核心模块
后端·c#·.net
唐青枫13 天前
别再乱用 StartNew:C#.NET TaskFactory 任务调度实战详解
c#·.net
Artech13 天前
[MAF预定义的AIContextProvider-03]ChatHistoryMemoryProvider——赋予Agent从经验中学习的能力
ai·c#·agent·memory·maf
Scout-leaf15 天前
C#摸鱼实录——IoC与DI案例详解
c#