【问题标题】:How to combine multiple Func<> delegates如何组合多个 Func<> 委托
【发布时间】:2020-08-12 20:25:44
【问题描述】:

如何合并多个 Func 委托?

假设我有两个代表

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

有没有办法将这两个代表合并为一个Func&lt;bool&gt; 代表?

类似:

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

或者

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

【问题讨论】:

  • 您只是缺少开头的() =&gt;
  • 您的初始代表也未正确定义。他们应该是Func&lt;bool&gt; MovementButtonHold = () =&gt; _inputSystem.MoveButtonHold;Func&lt;bool&gt; IsFreeAhead = () =&gt; _TPG.IsFreeAhead();
  • @juharr 这取决于它们是否被定义为方法。 (最近的语法糖)
  • @Nkosi 在这种情况下,将它们组合起来需要() =&gt; MovementButtonHold()() &amp;&amp; IsFreeAhead()();
  • 啊,我明白你的意思了。无论哪种方式,OP 都需要提供更多细节来阐明他们真正想要什么。

标签: c# .net unity3d predicate


【解决方案1】:

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

Func<bool> delegate1 = () => MovementButtonHold()() && IsFreeAhead()();
Func<bool> 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();

【讨论】:

    【解决方案2】:
        Func<bool> MovementButtonHold = () => true;
        Func<bool> IsFreeAhead = () => false;
        
        Func<bool> delegate1 = () => MovementButtonHold() && IsFreeAhead();
        Func<bool> delegate2 = () => MovementButtonHold() || IsFreeAhead();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-03
      • 1970-01-01
      • 1970-01-01
      • 2021-03-23
      • 1970-01-01
      相关资源
      最近更新 更多