从F#调用C#函数 [英] Calling C# functions from F#

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

问题描述

我试图从f#调用此函数

I was trying to call this function from f#

http://msdn.microsoft.com/zh-cn/library/microsoft.windowsazure.cloudstorageaccount.setconfigurationsettingpublisher.aspx

函数签名为:

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

如果要将setterFunc<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屋!

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