问题描述
我有一个如下所示的委托:
I have a delegate which looks like the following:
public delegate bool ApprovalPrompt(ApprovalType type, int receipt, params string[] info);
我接受这种类型的委托作为我要调用的函数的参数.但是,在一个特定的调用函数中,我想将一些额外的数据传递给与此委托匹配的函数.
I accept a delegate of this type as a parameter to the function I want to call. However, in one particular calling function, I want to pass some extra data to the function which matches this delegate.
这是实现函数的签名:
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
参数...
推荐答案
你可以使用 lambda 来curry"你的函数:
You can use a lambda to "curry" your function:
PrepareReceipt((type, receipt, info) =>
LogApprovalNeeded(myCustomer, type, receipt, info))
Currying 函数是存储对函数的引用但具有一个或多个固定"参数的正式术语,从而改变方法的签名.
Currying a function is the formal term for storing a reference to a function but with one or more of the parameters "fixed", thus altering the signature of the method.
当您的函数签名不需要委托提供的所有参数时,您也可以使用 lambda;您可以通过不传递 lambda 中的所有参数来有效地丢弃参数.
You can also use a lambda when the signature of your function doesn't need all of the arguments that the delegate is providing; you can effectively discard parameters by not passing forward all of the arguments in the lambda.
这篇关于传递带有额外参数的委托函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!