首页 > 解决方案 > 如何在 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

标签: f#

解决方案


如果您同时控制代码的 C# 和 F# 部分,那么我不会尝试从 C# 显式创建 F# 函数 - 这只会让您的 C# 代码变得丑陋。您可以轻松添加一个静态方法,该方法将采用FuncAction委托并提供 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# 中这样做并没有获得太多收益)。


推荐阅读