【问题标题】:execute c# method with multiple parameters from f#使用来自 f# 的多个参数执行 c# 方法
【发布时间】:2021-07-01 00:25:12
【问题描述】:

我是 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# 函数只接受单个参数,则此代码完美运行,例如:如果 C# 函数为 ... GiveMe(int count) 而 F# 代码为 ... FruitFactory.GiveMe 2 ,则一切正常!
  • 您可以在FSharpForFunAndProfit.com 阅读有关函数的信息。本文介绍 F# 中的函数以及如何使用它们。我建议阅读整个“Thinking functionally”系列以了解 F# 的核心原理

标签: f# c#-to-f#


【解决方案1】:

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

【讨论】:

  • 是的,它有效,谢谢。我希望执行像FruitFactory.GiveMe 2 "Apples" 这样的功能。有可能实现吗?
  • 太好了!请继续,我很想看看你想展示什么。
  • 好的,我已经更新了我的答案以展示它是如何完成的。我不推荐,但有可能。
  • 一般情况下,请不要删除 cmets。这让人很难理解对话。
  • 对不起,你是对的。缺少的评论说我可以展示如何在 C# 中创建一个柯里化函数。写完之后我就删了,因为我意识到我并不完全确定如何干净利落,但后来想通了。
【解决方案2】:

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

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

【讨论】:

  • 是的,它有效,谢谢。我希望执行FruitFactory.GiveMe 2 "Apples" 之类的功能。有可能实现吗?
猜你喜欢
  • 1970-01-01
  • 2017-09-25
  • 2013-12-24
  • 1970-01-01
  • 2017-08-15
  • 1970-01-01
  • 2013-02-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多