lambda之间的互操作

lambda之间的互操作

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

问题描述

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

如果我将带有签名'a->'b的F#函数发送给希望使用Func的C#方法,则F#编译器会产生以下错误:

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

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

解决方案

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

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))?

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

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# 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#lambda之间的互操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 00:10