C# 如何组合多个功能<&燃气轮机;代表

C# 如何组合多个功能<&燃气轮机;代表,c#,.net,unity3d,predicate,C#,.net,Unity3d,Predicate,如何组合多个Func委托 假设我有两名代表 Func<bool> MovementButtonHold() => () => _inputSystem.MoveButtonHold Func<bool> IsFreeAhead() => () => _TPG.IsFreeAhead(); Func MovementButtonHold()=>()=>\u inputSystem.MoveButtonHold Func IsFreeAhead()=

如何组合多个Func委托

假设我有两名代表

Func<bool> MovementButtonHold() => () => _inputSystem.MoveButtonHold
Func<bool> IsFreeAhead() => () => _TPG.IsFreeAhead();
Func MovementButtonHold()=>()=>\u inputSystem.MoveButtonHold
Func IsFreeAhead()=>()=>\u TPG.IsFreeAhead();
有没有办法将这两个委托合并为一个
Func
委托

比如:

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

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

在代码移动中,ButtonHold和IsFreeAhead不是委托,它们是返回委托的方法。 因此,要将它们结合在一起,您需要以下内容:

Func<bool> delegate1 = () => MovementButtonHold()() && IsFreeAhead()();
Func<bool> delegate2 = () => MovementButtonHold()() || IsFreeAhead()();
Func delegate1=()=>MovementButtonHold()()&&IsFreeAhead();
Func delegate2=()=>MovementButtonHold()| | IsFreeAhead();
注意上面的()奇怪语法。第一个()调用方法并返回委托,第二个()调用委托返回布尔结果。然后创建一个内联函数来对输出执行“AND”或“or”操作,并将内联函数分配给delegate1或delegate2

除非您有理由让MovementButtonHold和IsFreeAhead返回委托,否则您可以按如下方式简化它们的实现,以简单地返回布尔结果

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

Func<bool> delegate1 = () => MovementButtonHold() && IsFreeAhead();
Func<bool> delegate2 = () => MovementButtonHold() || IsFreeAhead();
bool MovementButtonHold()=>\u inputSystem.MoveButtonHold;
bool IsFreeAhead()=>\u TPG.IsFreeAhead();
Func delegate1=()=>MovementButtonHold()&&IsFreeAhead();
Func delegate2=()=>MovementButtonHold()| | IsFreeAhead();
Func MovementButtonHold=()=>true;
Func IsFreeAhead=()=>false;
Func delegate1=()=>MovementButtonHold()&&IsFreeAhead();
Func delegate2=()=>MovementButtonHold()| | IsFreeAhead();

您刚开始时缺少了
()=>
。而且您的初始委托定义不正确。它们应该是
Func MovementButtonHold=()=>\u inputSystem.MoveButtonHold
Func isfreeaward=()=>\u TPG.isfreeaward()@juharr,这取决于它们是否定义为方法。(最新语法sugar)@Nkosi在这种情况下组合它们需要
()=>MovementButtonHold()()&&isfreeaward()啊,我明白你的意思了。无论哪种方式,OP都需要提供更多细节,以澄清他们真正想要什么。
    Func<bool> MovementButtonHold = () => true;
    Func<bool> IsFreeAhead = () => false;
    
    Func<bool> delegate1 = () => MovementButtonHold() && IsFreeAhead();
    Func<bool> delegate2 = () => MovementButtonHold() || IsFreeAhead();