繁体   English   中英

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

[英]Call a higher order F# function from C#

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

let ApplyOn2 (f:int->int) = f(2)  

和C#功能

public static int Increment(int a) { return a++; } 

如何使用Increment作为参数调用ApplyOn2 (来自C#)? 请注意, ApplyOn2将导出为Microsoft.FSharp.Core.FSharpFunc<int,int> ,它与Increment的签名不匹配。

要从等效的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));

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

var cs_func = Microsoft.FSharp.Core.FSharpFunc<int,int>.ToConverter(fsharp_func);
int i = cs_func(2);

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

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

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

let ApplyOn2 (f : System.Func<int, int>) = f.Invoke(2)

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

MyFSharpModule.ApplyOn2(Increment); // 3

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

public static int Increment(int a) { return ++a; }

只需创建对程序集的引用:

#r @"Path\To\Your\Library.dll"
let ApplyOn2 (f:int->int) = f(2)
ApplyOn2 Library.Class.Increment

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM