从 C# 调用高阶 F# 函数

2024-05-12

给定 F# 高阶函数(在参数中采用函数):

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

和 C# 函数

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

我怎么打电话ApplyOn2 with Increment作为参数(来自 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)));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

从 C# 调用高阶 F# 函数 的相关文章

随机推荐