【问题标题】:Passing delegate function with extra parameters传递带有额外参数的委托函数
【发布时间】:2018-07-26 02:15:03
【问题描述】:

我有一个如下所示的委托:

public delegate bool ApprovalPrompt(ApprovalType type, int receipt, params string[] info);

我接受这种类型的委托作为我要调用的函数的参数。但是,在一个特定的调用函数中,我想将一些额外的数据传递给与此委托匹配的函数。

这是实现函数的签名:

private static bool LogApprovalNeeded(FraudFilterUtilities.ApprovalType type, int receipt, params string[] info)

它的调用方式如下:

PrepareReceipt(LogApprovalNeeded);

我希望它是:

private static bool LogApprovalNeeded(Customer cust, FraudFilterUtilities.ApprovalType type, int receipt, params string[] info)

理想情况下使用如下:

PrepareReceipt(LogApprovalNeeded(myCustomer))

我怎样才能完成这样的事情?我宁愿不需要在类中声明一个字段只是为了在一个函数和回调之间保存Customer 参数...

【问题讨论】:

    标签: c# delegates


    【解决方案1】:

    您可以使用 lambda 来“咖喱”您的函数:

    PrepareReceipt((type, receipt, info) => 
        LogApprovalNeeded(myCustomer, type, receipt, info))
    

    Currying a function 是存储对函数的引用但具有一个或多个“固定”参数的正式术语,从而改变方法的签名。

    当您的函数签名不需要委托提供的所有参数时,您也可以使用 lambda;您可以通过不传递 lambda 中的所有参数来有效地丢弃参数。

    【讨论】:

    • 我知道它必须以某种方式成为可能。谢谢!
    • PrepareReceipt 的签名是什么样的?
    • @mcmillab 参数为ApprovalPrompt。
    【解决方案2】:

    您可以使用 lambda 来实现您所需要的。

    PrepareReceipt((type, receipt, info) =>
                   LogApprovalNeeded(myCustomer, type, receipt, info));
    

    或者,将您的 LogApprovalNeeded 签名更改为:

    static bool LogApprovalNeeded(ApprovalType type, int receipt, 
                                  Customer cust = null, params string[] info)
    {
    }
    

    但考虑到您已经在cust 之后定义了可变数量的参数,它可能会有点混乱。

    编辑: 正如 Servy 正确指出的那样,签名的更改不会让您按照您的描述调用该方法。但是,如果将与Customer 相关的逻辑移动到PrepareReceipt,则不需要使用上述方法(它基本上会生成一个新的匿名方法并将myCustomer 包装在一个闭包中。

    【讨论】:

    • @Servy 同意,不会按照作者描述的方式工作,我会指出来。但是,如果他可以将涉及Customer 的逻辑封装在PrepareReceipt 中,那么他就不需要curry 他的调用了。
    • +1 - 很好的答案,我很欣赏这个替代方案(虽然我绝对同意它会令人困惑),但我会接受 Servy 的,因为他也包含了官方术语。
    • @Eve - 我真的希望我可以封装它,但是由于我们拥有旧代码和新代码的混合,PrepareReceipt 无法与 Customer 对象一起使用。或者至少,它不能这样做。
    【解决方案3】:

    如果您需要代理部分应用程序的通用解决方案(减少参数),请查看NReco Commons 开源库,它包含可以对任何代理类型执行此操作的 PartialDelegateAdapter:

    var logApprovalForCustomer = (new PartialDelegateAdapter(LogApprovalNeeded,
        new[] {myCustomer})).GetDelegate<Func<FraudFilterUtilities.ApprovalType,int,string[],bool>>();
    

    在此示例中,第一个参数固定为 myCustomer 值。此外,它还尝试在运行时协调参数类型。

    【讨论】:

      【解决方案4】:

      Lamba 方法并不完美:它们没有属性并且会导致代码混乱。
      如果你想避免这种方法,你可以用另一种方式来做,就像 JavaScript 的 .bind() 函数。
      该函数可以在 C# 中进行如下调整,使用带有一些扩展方法的静态类:

      //This code requires the Nu-get plugin ValueTuple
      using System.Diagnostics;
      
      public static class Extensions
      {
      
          [DebuggerHidden, DebuggerStepperBoundary]
          public static WaitCallback Bind(this Delegate @delegate, params object[] arguments)
          {
              return (@delegate, arguments).BoundVoid;
          }
      
          [DebuggerHidden, DebuggerStepperBoundary]
          public static Func<object, object> BindWithResult(this Delegate @delegate, params object[] arguments)
          {
              return (@delegate, arguments).BoundFunc;
          }
      
          [DebuggerHidden, DebuggerStepperBoundary]
          private static void BoundVoid(this object tuple, object argument)
          {
              tuple.BoundFunc(argument);
          }
      
          [DebuggerHidden, DebuggerStepperBoundary]
          private static object BoundFunc(this object tuple, object argument)
          {
              (Delegate @delegate, object[] arguments) = ((Delegate @delegate, object[] arguments))tuple;
              if (argument != null)
                  if (!argument.GetType().IsArray)
                      argument = new object[] { argument };
              object[] extraArguments = argument as object[];
              object[] newArgs = extraArguments == null ? arguments : new object[arguments.Length + extraArguments.Length];
              if (extraArguments != null)
              {
                  extraArguments.CopyTo(newArgs, 0);
                  arguments.CopyTo(newArgs, extraArguments.Length);
              }
              if (extraArguments == null)
                  return @delegate.DynamicInvoke(newArgs);
              object result = null;
              Exception e = null;
              int argCount = newArgs.Length;
              do
              {
                  try
                  {
                      if (argCount < newArgs.Length)
                      {
                          object[] args = newArgs;
                          newArgs = new object[argCount];
                          Array.Copy(args, newArgs, argCount);
                      }
                      result = @delegate.DynamicInvoke(newArgs);
                      e = null;
                  } catch (TargetParameterCountException e2)
                  {
                      e = e2;
                      argCount--;
                  }
              } while (e != null);
              return result;
          }
      }
      

      现在您可以为您的方法(不是 lambda)创建一个委托并为其分配一些固定参数:

      MessageBox.Show(new Func<double, double, double>(Math.Pow).BindWithResult(3, 2)(null).ToString()); //This shows you a message box with the operation 3 pow 2
      

      所以,下面的代码将产生一个WaitCallback 委托:

      new Func<double, double, double>(Math.Pow).Bind(3, 2)
      

      而下面的代码将产生一个Func&lt;object, object&gt; 委托:

      new Func<double, double, double>(Math.Pow).BindWithResult(3, 2)
      

      【讨论】:

        【解决方案5】:

        您可以更改PrepareReceipt 函数以获取附加参数。签名看起来类似于 public void PrepareReceipt(Customer customer, ApprovalPrompt approvalPrompt) 来完成此操作。

        【讨论】:

        • 如果函数不需要这个参数,那么这不是合适的做法。它充其量只会在其他使用它的地方引起混乱。
        【解决方案6】:

        您不能将其传递给该委托,因为该委托未声明客户类型的参数。 “简单的答案”是更改委托的签名以采用新参数。

        也就是说,这也需要修改委托的所有消费者。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-11-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-02-27
          • 1970-01-01
          相关资源
          最近更新 更多