c# - 如何组合多个 Func<> 委托(delegate)

标签 c# .net unity-game-engine predicate

如何组合多个 Func 委托(delegate)?

假设我有两名代表

Func<bool> MovementButtonHold() => () => _inputSystem.MoveButtonHold
Func<bool> IsFreeAhead() => () => _TPG.IsFreeAhead();

有没有办法将这两个代表合并为一个 Func<bool>代表?

类似于:

还有

Func<bool> delegate1 = MovementButtonHold() && IsFreeAhead();

或者

Func<bool> delegate2 = MovementButtonHold() || IsFreeAhead();

最佳答案

在您的代码中,MovementButtonHold 和 IsFreeAhead 不是委托(delegate),它们是返回委托(delegate)的方法。 因此,要将它们结合起来,您需要这样的东西:

Func<bool> delegate1 = () => MovementButtonHold()() && IsFreeAhead()();
Func<bool> delegate2 = () => MovementButtonHold()() || IsFreeAhead()();

请注意上面 ()() 奇怪的语法。第一个 () 是调用方法并返回委托(delegate),第二个 () 是调用委托(delegate)返回 bool 结果。然后创建一个内联函数对输出执行“AND”或“OR”运算,并将内联函数分配给 delegate1 或 delegate2

除非您有理由让 MovementButtonHold 和 IsFreeAhead 返回委托(delegate),否则您可以按如下方式简化其实现,以仅返回 bool 结果。

bool MovementButtonHold() => _inputSystem.MoveButtonHold;
bool IsFreeAhead() => _TPG.IsFreeAhead();

Func<bool> delegate1 = () => MovementButtonHold() && IsFreeAhead();
Func<bool> delegate2 = () => MovementButtonHold() || IsFreeAhead();

关于c# - 如何组合多个 Func<> 委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63384257/

相关文章:

.net - 如何在 F# 中编写内联大字符串

c# - Nhibernate 事务 :Avoiding Nhibernate dependency in the service layer

c# - 正则表达式:保留未知子字符串

c# - 你如何在 C# 中返回 'not uint'?

.net - XAML 中以逗号分隔的字符串形式的字符串数组

unity-game-engine - 我的 Canvas 因遮挡而消失

unity-game-engine - Unity 网络 Material 颜色更改不起作用

c# - 从 Unity 3D 游戏在 IOS 上保存文件

C# 存储数字的安全方式?

c# - 如何使用 Moq 模拟包含内部抽象方法的抽象类?