从F#调用C#函数 [英] Calling C# functions from F#
问题描述
我试图从f#调用此函数
I was trying to call this function from f#
函数签名为:
CloudStorageAccount.SetConfigurationSettingPublisher
(Action<string, Func<string, bool>>) : unit
C#调用如下所示:
CloudStorageAccount.SetConfigurationSettingPublisher((configName,
configSettingPublisher) =>
{
string configValue = "something"
configSettingPublisher(configValue);
});
而在F#中,我必须做这样的事情:
whereas in F#, I had to do something like this:
let myPublisher configName (setter:Func<string, bool>) =
let configValue = RoleEnvironment.GetConfigurationSettingValue(configName)
setter.Invoke(configName) |> ignore
let act = new Action<string, Func<string, bool>>(myPublisher)
CloudStorageAccount.SetConfigurationSettingPublisher(act)
可以在f#中更简洁地编写吗?
Can this be written more concisely in f#?
推荐答案
F#自动将使用fun ... -> ...
语法创建的Lambda函数转换为.NET委托类型,例如Action
.这意味着您可以像这样直接将lambda函数用作SetConfigurationSettingPublisher
的参数:
F# automatically converts lambda functions created using the fun ... -> ...
syntax to .NET delegate types such as Action
. This means that you can use lambda function as an argument to SetConfigurationSettingPublisher
directly like this:
CloudStorageAccount.SetConfigurationSettingPublisher(fun configName setter ->
let configValue = RoleEnvironment.GetConfigurationSettingValue(configName)
setter.Invoke(configName) |> ignore)
具有多个参数的函数可以转换为具有多个参数的委托(这些参数不应视为元组). setter
的类型仍然是Func<...>
,而不是简单的F#函数,因此您需要使用Invoke
方法来调用它(但这没什么大不了的.)
A function of multiple arguments can be converted to a delegate of multiple arguments (the arguments shouldn't be treated as a tuple). The type of setter
is still Func<...>
and not a simple F# function, so you need to call it using the Invoke
method (but that shouldn't be a big deal).
如果要将setter
从Func<string, bool>
转换为F#函数string -> bool
,则可以定义一个简单的活动模式:
If you want to turn setter
from Func<string, bool>
to an F# function string -> bool
, you can define a simple active pattern:
let (|Func2|) (f:Func<_, _>) a = f.Invoke(a)
...然后您可以编写:
...and then you can write:
TestLib.A.SetConfigurationSettingPublisher(fun configName (Func2 setter) ->
let configValue = "aa"
setter(configName) |> ignore)
这篇关于从F#调用C#函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!