Interop between F# and C# lambdas

徘徊边缘 提交于 2020-01-27 22:40:56

问题


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?


回答1:


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>.



来源:https://stackoverflow.com/questions/3392000/interop-between-f-and-c-sharp-lambdas

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!