Passing delegate function with extra parameters(传递带有额外参数的委托函数)
问题描述
我有一个如下所示的委托:
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.
这篇关于传递带有额外参数的委托函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:传递带有额外参数的委托函数


基础教程推荐
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01