传递带有额外参数的委托函数

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.

这篇关于传递带有额外参数的委托函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)