F# 和 C# lambdas 之间的互操作 [英] Interop between F# and C# lambdas

查看:25
本文介绍了F# 和 C# lambdas 之间的互操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

F# powerpack 带有一组转换方法,可将 Func<...> 转换为 F# 函数,标准函数或元组函数.但是否有可能实现相反的目标:如果您想从 F# 代码调用一个采用 Func<...> 的 C# 方法,并想使用原生 F# lambda 表达式(例如 fun x -> some_function_of(x))?

F# powerpack comes with a set of conversion methods to translate from Func<...> to F# functions, either standard or tupled ones. But is it possible to achieve the opposite: in case you want to call from F# code a C# method that takes Func<...> and want to use native F# lambda expression (e.g. fun x -> some_function_of(x))?

如果我将带有签名 'a -> 'b 的 F# 函数发送到需要 Func 的 C# 方法,则 F# 编译器会生成以下错误:

If I send a F# function with a signature 'a -> 'b to a C# method that expects Func then F# compiler generates the following error:

This expression was expected to have type Function<'T,'R> but here has type 'T -> 'R

我想继续使用 F# lambda 表达式,但要使用翻译层,以便能够将它们作为 C# Func lambda 发送.这可以实现吗?

I want to stay with F# lambda expressions but to use a translation layer in order to be able to send them as C# Func lambda. Is this achievable?

推荐答案

F# 为所有采用相应函数类型的 F# 值的委托类型提供构造函数.例如.在您的情况下,您想使用 System.Func<_,_>(fun x -> ...) 它应用生成的 ('a -> 'b) ->System.Func<'a, 'b>.

F# provides constructors for all delegate types that take F# values of the corresponding function types. E.g. in your case you want to use System.Func<_,_>(fun x -> ...) which applies the generated constructor of type ('a -> 'b) -> System.Func<'a, 'b>.

这篇关于F# 和 C# lambdas 之间的互操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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