如何组合多个 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/