从C#调用更高阶的F#函数

sth*_*ers 19 c# f# delegates

给定F#高阶函数(在参数中取一个函数):

let ApplyOn2 (f:int->int) = f(2)  
Run Code Online (Sandbox Code Playgroud)

和C#功能

public static int Increment(int a) { return a++; } 
Run Code Online (Sandbox Code Playgroud)

我如何打电话ApplyOn2Increment作为参数(从C#)?请注意,ApplyOn2 导出的签名Microsoft.FSharp.Core.FSharpFunc<int,int>Increment签名不匹配.

HS.*_*HS. 29

要从等效的C#函数中获取FSharpFunc,请使用:

Func<int,int> cs_func = (i) => ++i;
var fsharp_func = Microsoft.FSharp.Core.FSharpFunc<int,int>.FromConverter(
    new Converter<int,int>(cs_func));
Run Code Online (Sandbox Code Playgroud)

要从等效的FSharpFunc获取C#函数,请使用

var cs_func = Microsoft.FSharp.Core.FSharpFunc<int,int>.ToConverter(fsharp_func);
int i = cs_func(2);
Run Code Online (Sandbox Code Playgroud)

所以,在这种特殊情况下,您的代码可能如下所示:

Func<int, int> cs_func = (int i) => ++i;
int result = ApplyOn22(Microsoft.FSharp.Core.FSharpFunc<int, int>.FromConverter(
            new Converter<int, int>(cs_func)));
Run Code Online (Sandbox Code Playgroud)


Ray*_*gus 17

如果您想提供更友好的互操作体验,请考虑直接在F#中使用System.Func委托类型:

let ApplyOn2 (f : System.Func<int, int>) = f.Invoke(2)
Run Code Online (Sandbox Code Playgroud)

您可以在C#中轻松调用F#函数,如下所示:

MyFSharpModule.ApplyOn2(Increment); // 3
Run Code Online (Sandbox Code Playgroud)

但是,您已经编写了增量函数的问题.您需要增量运算符的前缀形式,以便您的函数返回正确的结果:

public static int Increment(int a) { return ++a; }
Run Code Online (Sandbox Code Playgroud)