从C#调用更高阶的F#函数 [英] Call a higher order F# function from C#

查看:101
本文介绍了从C#调用更高阶的F#函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出F#高阶函数(在参数中使用函数):

Given the F# higher order function (taking a function in parameter):

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

和C#函数

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

我如何通过<< c>调用 ApplyOn2 code>增量作为参数(来自C#)?
请注意, ApplyOn2 导出为 Microsoft.FSharp.Core.FSharpFunc< int,int> 增量的签名不匹配。

How do I call ApplyOn2 with Increment as parameter (from C#)? Note that ApplyOn2 is exported as Microsoft.FSharp.Core.FSharpFunc<int,int> which do not match with Increment's signature.

推荐答案

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

If you would like to provide a more friendly interop experience, consider using the System.Func delegate type directly in F#:

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

您的F#函数在C#中非常容易地像这样:

You would be able to call your F# function very easily in C# like this:

MyFSharpModule.ApplyOn2(Increment); // 3

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

There is an issue with the Increment function as you have written it, however. You need the prefix form of the increment operator in order for your function to return the correct result:

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

这篇关于从C#调用更高阶的F#函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆