使用来自 f# C# 项目F# 项目

问题描述

我是 F# 新手,我正在尝试执行一个静态 C# 函数,该函数接受来自 F# 文件/代码的多个参数。

我有一个包含 C# 项目和 F# 项目的解决方案。

C# 项目

来自 C# 文件代码

using ...

namespace Factories
{
    public static class FruitFactory
    {
        public static string GiveMe(int count,string fruitname)
        {
            ...
            ...
            return ... (string) ...
        }
    }
}

F# 项目

来自 F# 文件代码

open System
open Factories

[<EntryPoint>]
let main argv =
    let result = FruitFactory.GiveMe 2 "Apples"
    printfn "%s" result
    printfn "Closing Fruit Factory!"
    0

从上面的代码片段中,我收到代码 let result = FruitFactory.GiveMe 2 "Apples"

的以下错误

错误 1:

  Program.fs(6,37): [FS0001] This expression was expected to have type
    'int * string'    
but here has type
    'int'

错误 2:

Program.fs(6,18): [FS0003] This value is not a function and cannot be applied.

解决方法

C# 函数是非柯里化的,因此您必须像使用元组一样调用它,如下所示:FruitFactory.GiveMe(2,"Apples")

如果您真的想创建一个可以使用 F# 中的柯里化参数调用的 C# 函数,您必须分别处理每个参数。它不漂亮,但可以这样做:

C# 项目

using Microsoft.FSharp.Core;

public static class FruitFactory
{
    /// <summary>
    /// Curried version takes the first argument and returns a lambda
    /// that takes the second argument and returns the result.
    /// </summary>
    public static FSharpFunc<string,string> GiveMe(int count)
    {
        return FuncConvert.FromFunc(
            (string fruitname) => $"{count} {fruitname}s");
    }
}

F# 项目

然后您可以在 F# 中以您想要的方式调用它:

let result = FruitFactory.GiveMe 2 "Apple"
printfn "%s" result
,

多参数 .NET 方法在 F# 中显示为具有元组参数的方法:

let result = FruitFactory.GiveMe(2,"Apples")