f# - 如何在 C# 中实现 F# 高阶函数?
问题描述
如何在 C# 中实现 F#高阶函数?
public ICommand RequestAccount =
new DelegateCommand(FuncConvert.ToFSharpFunc( _ => Debug.WriteLine() ),
FuncConvert.ToFSharpFunc( _ => return true )
);
错误 CS0411 无法从用法推断方法“FuncConvert.ToFSharpFunc(Action)”的类型参数。尝试明确指定类型参数。
基于错误,我不知道如何明确表达类型参数。因此,我不认为 C# 理解在第一个 lambda 上返回的单位是什么。
委托命令
type DelegateCommand (action:(obj -> unit), canExecute:(obj -> bool)) =
let event = new DelegateEvent<EventHandler>()
interface ICommand with
[<CLIEvent>]
member this.CanExecuteChanged = event.Publish
member this.CanExecute arg = canExecute(arg)
member this.Execute arg = action(arg
解决方案
如果您同时控制代码的 C# 和 F# 部分,那么我不会尝试从 C# 显式创建 F# 函数 - 这只会让您的 C# 代码变得丑陋。您可以轻松添加一个静态方法,该方法将采用Func
和Action
委托并提供 C# 友好的接口:
type DelegateCommand (action:(obj -> unit), canExecute:(obj -> bool)) =
let event = new DelegateEvent<EventHandler>()
interface ICommand with
[<CLIEvent>]
member this.CanExecuteChanged = event.Publish
member this.CanExecute arg = canExecute(arg)
member this.Execute arg = action(arg)
static member Create(action:Action<obj>, canExecute:Func<obj, bool>) =
DelegateCommand(action.Invoke, canExecute.Invoke)
现在您可以DelegateCommand.Create
从 C# 以一种很好的方式使用:
DelegateCommand.Create(
(o => Console.WriteLine(o)),
(o => true) )
作为记录,我也不太明白DelegateCommand
在 F# 中定义并在 C# 中使用它的价值,如果你没有在 F# 端做任何其他事情 - 它似乎是一个可以在 C# 中定义的简单类型(即你在 F# 中这样做并没有获得太多收益)。
推荐阅读
- regex - 如何使用忽略的单词作为匹配的分隔符
- excel - 如何将 Merge 函数应用于使用 InputBox 从用户中选择的 Range 对象?
- python - 如何将两个列表条目添加到 CSV 文件中,每个条目位于不同的标题下?
- python - 通过 .loc 对 Panda 切片进行矩阵运算的有效方法
- excel - 如何在 Excel 上使用 vba 从字符串中提取电话号码和姓名
- regex - 如何在 perl 正则表达式中使用 unicode
- sql-server - 如何将混合匹配日期转换为 ssis 中的一个统一日期?
- javascript - 将父组件(即“this”)作为 React 中的 prop 完全传递给子组件是不是很糟糕?
- ruby-on-rails - 没有路线匹配 [POST] '/users/new'
- javascript - 未捕获的错误:Tabledit 仅在应用于表时有效