Skip to content

Func

csharp-func-deep-dive

Func 是什么

Func 是 C# 内置的委托类型,专门保存“有返回值的方法”。

Action 的区别很简单:

c
Action      // 做一件事,但不返回结果
Func        // 做一件事,并返回结果

比如:

c
using System;

Func<int> getScore = () => 100;
int score = getScore(); // score = 100

最重要规则

Func 的最后一个泛型类型,永远是返回值类型。

c
Func<int>                 // 无参数,返回 int
Func<int, bool>           // 传入 int,返回 bool
Func<int, int, int>       // 传入 int、int,返回 int
Func<string, int, bool>   // 传入 string、int,返回 bool

比如:

c
Func<int, bool> isAlive = hp => hp > 0;

bool result = isAlive(100); // true

这里 int 是输入参数,bool 是返回值。

方法名也可以赋给 Func

c
Func<int, bool> checkHp = IsAlive;

bool IsAlive(int hp)
{
    return hp > 0;
}

只要方法签名匹配就行:

c
Func<int, bool>

意思是:接收一个 int,返回一个 bool

Unity 里怎么用

Unity 里,Func 常用来表示“规则”“条件”“公式”“读取值”。

例如攻击条件:

c
using System;
using UnityEngine;

public class Skill : MonoBehaviour
{
    public Func<bool> CanUse;

    public void TryUse()
    {
        if (CanUse != null && CanUse())
        {
            Debug.Log("释放技能");
        }
    }
}

外部可以这样传规则:

skill.CanUse = () => player.Mp >= 10 && enemy != null;

这样 Skill 不需要知道具体怎么判断,它只负责问一句:现在能不能用?

再看一个伤害公式

c
Func<int, int, int> calculateDamage;

calculateDamage = (attack, defense) =>
{
    return attack - defense;
};

int damage = calculateDamage(50, 20); // 30

这里:

attack 是第一个 intdefense 是第二个 int 最后一个 int 是返回值

什么时候用 Func

需要“算出结果”时用 Func。 只需要“执行动作”时用 Action。 需要“通知别人发生了什么”时,常用 event Action。 需要公开 API 更清楚时,可以自定义 delegate

新手最容易错的地方

Func<int, bool> 不是返回 int,而是传入 int,返回 bool

Func 不能表示 void 方法。没有返回值就用 Action

不要在 Update() 里频繁创建复杂 lambda,尤其是捕获外部变量时,可能带来额外分配和性能压力。

官方参考:

Microsoft - FuncMicrosoft - FuncMicrosoft - DelegatesMicrosoft - Lambda expressionsMicrosoft - Action

文章评价

读完这篇,留下你的看法

暂无审核通过的评价。

登录账号后才能评价。

本站访客数0总站访问量0本页访问量0