问题描述
我有一个类似于以下内容的委托:
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来咖喱您的函数:
You can use a lambda to "curry" your function:
PrepareReceipt((type, receipt, info) =>
LogApprovalNeeded(myCustomer, type, receipt, info))
使用函数是存储对函数的引用但具有一个或多个参数 fixed的正式术语,从而更改了方法的签名。
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.
这篇关于传递带有附加参数的委托函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!