在.net4.0中从C#调用F#Sharp [英] Calling F# sharp from C# in .net4.0

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

问题描述

我们如何从C#编码中调用F#函数.

How we can call F# functions from C# coding.

推荐答案

从此处开始: ^ ].

Google是您的朋友.
Start here: Call F# code from C#[^].

Google is your friend.


1)在您的项目中添加引用FSharp.Core dll
2)在您的代码中引用Microsoft.FSharp.Core命名空间
1) Add a reference FSharp.Core dll in your project
2) Reference Microsoft.FSharp.Core namespace in your code
using FS = Microsoft.FSharp.Core;



3)实现您的功能,例如:



3) Implement your function, for example:

public static IEnumerable<U> map<T, U>(FS.FSharpFunc<T, U> mapper, 
 IEnumerable<T> input)
{
    foreach (T el in input)
    {
        yield return mapper.Invoke(el);
    }
}





注意:.Net运行时的版本会有所不同
(4.0与3.5)
奖金:从C#代码返回F#函数.

您还可以在C#代码中实现F#函数,并将它们传递给F#





Note: there are differences depending on the version of the .Net runtime
(4.0 vs. 3.5)
Bonus: return F# functions from C# code.

You can also implement F# functions in C# code and pass them to F#

//this is unit->string in F# speak
public class ReturnString: FSharpFunc<Unit, string>
{
    public FSharpFunc<Unit,string> asFSharpFunc()
    {
        return this;
    }

    public override string Invoke(Unit unitVar0)
    {
        return "a string";
    }
}



在F#中执行:



In F# do:

let funcFromCSharp = (ReturnString()).asFSharpFunc() //get it
funcFromCSharp () //call it



或这个



or this

let inline toFunc<''a,''b,''c when ''c :> FSharpFunc<''a,''b>> (x: ''c ): (''a -> ''b) = (# "" x : ''a -> ''b #)


let funcFromCSharp = ReturnString()|> toFunc
funcFromCSharp () //call it


这篇关于在.net4.0中从C#调用F#Sharp的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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