从C#调用F#代码

82

我在尝试使用 F# 和 C# 编程语言,并且希望能够从 C# 调用 F# 代码。

在 Visual Studio 中,我设法通过将两个项目放在同一解决方案中,并向 F# 项目添加 C# 代码的引用来实现另一种方式。 这样做后,我可以调用 C# 代码,甚至在调试时逐步执行它。

我现在正在尝试的是从 C# 调用 F# 代码,而不是从 F# 调用 C# 代码。 我已经向 C# 项目添加了对 F# 项目的引用,但它没有像之前那样工作。 我想知道是否有可能在不手动操作的情况下实现这一点。


10
除非你有特定的问题,否则从C#项目中引用F#项目今天“只需要工作”。这里没有什么非同寻常的地方,因为这是.NET架构的基本承诺或好处之一(语言无关、MSIL等)。事实上,相反的情况才会很奇怪。你还希望获得什么额外的回报? - Simon Mourier
4个回答

59
以下是从C#调用F#的工作示例。
正如您遇到的那样,我无法通过从“添加引用...项目”选项卡中选择来添加引用。相反,我必须手动执行它,通过在“添加引用...浏览”选项卡中浏览到F#程序集。
------ F# 模块 -----
// First implement a foldl function, with the signature (a->b->a) -> a -> [b] -> a
// Now use your foldl function to implement a map function, with the signature (a->b) -> [a] -> [b]
// Finally use your map function to convert an array of strings to upper case
//
// Test cases are in TestFoldMapUCase.cs
//
// Note: F# provides standard implementations of the fold and map operations, but the 
// exercise here is to build them up from primitive elements...

module FoldMapUCase.Zumbro
#light


let AlwaysTwo =
   2

let rec foldl fn seed vals = 
   match vals with
   | head :: tail -> foldl fn (fn seed head) tail
   | _ -> seed


let map fn vals =
   let gn lst x =
      fn( x ) :: lst
   List.rev (foldl gn [] vals)


let ucase vals =
   map String.uppercase vals

----- 模块的C#单元测试 -----

// Test cases for FoldMapUCase.fs
//
// For this example, I have written my NUnit test cases in C#.  This requires constructing some F#
// types in order to invoke the F# functions under test.


using System;
using Microsoft.FSharp.Core;
using Microsoft.FSharp.Collections;
using NUnit.Framework;

namespace FoldMapUCase
{
    [TestFixture]
    public class TestFoldMapUCase
    {
        public TestFoldMapUCase()
        {            
        }

        [Test]
        public void CheckAlwaysTwo()
        {
            // simple example to show how to access F# function from C#
            int n = Zumbro.AlwaysTwo;
            Assert.AreEqual(2, n);
        }

        class Helper<T>
        {
            public static List<T> mkList(params T[] ar)
            {
                List<T> foo = List<T>.Nil;
                for (int n = ar.Length - 1; n >= 0; n--)
                    foo = List<T>.Cons(ar[n], foo);
                return foo;
            }
        }


        [Test]
        public void foldl1()
        {
            int seed = 64;
            List<int> values = Helper<int>.mkList( 4, 2, 4 );
            FastFunc<int, FastFunc<int,int>> fn =
                FuncConvert.ToFastFunc( (Converter<int,int,int>) delegate( int a, int b ) { return a/b; } );

            int result = Zumbro.foldl<int, int>( fn, seed, values);
            Assert.AreEqual(2, result);
        }

        [Test]
        public void foldl0()
        {
            string seed = "hi mom";
            List<string> values = Helper<string>.mkList();
            FastFunc<string, FastFunc<string, string>> fn =
                FuncConvert.ToFastFunc((Converter<string, string, string>)delegate(string a, string b) { throw new Exception("should never be invoked"); });

            string result = Zumbro.foldl<string, string>(fn, seed, values);
            Assert.AreEqual(seed, result);
        }

        [Test]
        public void map()
        {
            FastFunc<int, int> fn =
                FuncConvert.ToFastFunc((Converter<int, int>)delegate(int a) { return a*a; });

            List<int> vals = Helper<int>.mkList(1, 2, 3);
            List<int> res = Zumbro.map<int, int>(fn, vals);

            Assert.AreEqual(res.Length, 3);
            Assert.AreEqual(1, res.Head);
            Assert.AreEqual(4, res.Tail.Head);
            Assert.AreEqual(9, res.Tail.Tail.Head);
        }

        [Test]
        public void ucase()
        {
            List<string> vals = Helper<string>.mkList("arnold", "BOB", "crAIg");
            List<string> exp = Helper<string>.mkList( "ARNOLD", "BOB", "CRAIG" );
            List<string> res = Zumbro.ucase(vals);
            Assert.AreEqual(exp.Length, res.Length);
            Assert.AreEqual(exp.Head, res.Head);
            Assert.AreEqual(exp.Tail.Head, res.Tail.Head);
            Assert.AreEqual(exp.Tail.Tail.Head, res.Tail.Tail.Head);
        }

    }
}

1
谢谢。对我来说,“我确实不得不手动完成,通过在“添加引用...浏览”选项卡中浏览F#程序集。” - ZeroKelvin

29

虽然你可能需要在从 C# 引用项目之前构建 F# 项目,但它应该“只是工作”(我忘了)。

常见的问题源头是命名空间/模块。如果你的 F# 代码没有以命名空间声明开头,则会将其放置在一个与文件名相同的模块中,因此从 C# 中访问你的类型可能会显示为“Program.Foo”,而不仅仅是“Foo”(如果 Foo 是在 Program.fs 中定义的 F# 类型)。


2
谢谢您提供有关模块名称的信息 :)。 - ZeroKelvin
2
是的,我需要写一篇博客来解释这个问题,因为它引起了很多困惑。 - Brian
当F#项目(生成DLL引用的项目)与C#项目(使用该DLL的项目)在同一个解决方案中时,会触发其他问题。 - George Kargakis
在使用project<=project ref之前,我必须先构建F#项目。 - derekbaker783

6
这个链接来看,他们似乎有多种可能的解决方案,但最简单的一个是一个注释:

F# 代码:

type FCallback = delegate of int*int -> int;;
type FCallback =
  delegate of int * int -> int

let f3 (f:FCallback) a b = f.Invoke(a,b);;
val f3 : FCallback -> int -> int -> int

C#代码:

int a = Module1.f3(Module1.f2, 10, 20); // method gets converted to the delegate automatically in C#

我在val行上遇到了错误:val f3: FCallback -> int -> int -> int。"错误1:定义中出现意外的关键字'val'。在此点之前或其他标记处,期望不完整的结构化构造。" - Tom Stickel

4

// Test.fs :

module meGlobal

type meList() = 
    member this.quicksort = function
        | [] -> []  //  if list is empty return list
        | first::rest -> 
            let smaller,larger = List.partition((>=) first) rest
        List.concat[this.quicksort smaller; [first]; this.quicksort larger]

// Test.cs :

List<int> A = new List<int> { 13, 23, 7, 2 };
meGlobal.meList S = new meGlobal.meList();

var cquicksort = Microsoft.FSharp.Core.FSharpFunc<FSharpList<IComparable>,     FSharpList<IComparable>>.ToConverter(S.quicksort);

FSharpList<IComparable> FI = ListModule.OfSeq(A.Cast<IComparable>());
var R = cquicksort(FI);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接