c# - 从 C# 调用 F# 库

标签 c# f#

我有一个由 C# 使用的 F# 类库。

F# 库有 2 种类型和一种我想从我的 C# 代码中调用的简单函数。

命名空间 HFNZ.InfectionStatus.ClassLibrary

type Result = 
    | Positive
    | Negative

type TestType = 
    | AntiHBc of Option<Result>
    | AntiHBs of Option<Result>
    | HBeAg of Option<Result>
    | HBsAg of Option<Result>
    | HBVDNA of Option<Result>

module Program =

    let getHVBStatus (test1, test2, test3, test4, test5) =
        match test1 test2 test3 test4 test5 with
        | AntiHBc   (Some(Positive)), 
          AntiHBs   (Some(Positive)), 
          HBeAg     (Some(Positive)), 
          HBsAg     (Some(Positive)), 
          HBVDNA    (Some(Positive))  -> "Normal"

        | _ -> "Elevated"

这是我的 C# 代码:

var positive = new FSharpOption<Result>(Result.Positive);
var antiHBc =  TestType.NewAntiHBc(positive);
var AntiHBs = TestType.NewAntiHBs(positive);
var HBeAg = TestType.NewHBeAg(positive);
var HBsAg = TestType.NewHBsAg(positive);
var HBVDNA = TestType.NewHBVDNA(positive);

Program.getHVBStatus(antiHBc, AntiHBs, HBeAg, HBsAg, HBVDNA);

由于此错误,C# 代码无法编译:

Severity    Code    Description Project File    Line    Suppression State
Error   CS1503  Argument 1: cannot convert from 'InfectionStatus.ClassLibrary.TestType' to 'Microsoft.FSharp.Core.FSharpFunc<InfectionStatus.ClassLibrary.TestType, Microsoft.FSharp.Core.FSharpFunc<InfectionStatus.ClassLibrary.TestType, Microsoft.FSharp.Core.FSharpFunc<InfectionStatus.ClassLibrary.TestType, Microsoft.FSharp.Core.FSharpFunc<InfectionStatus.ClassLibrary.TestType, System.Tuple<InfectionStatus.ClassLibrary.TestType, InfectionStatus.ClassLibrary.TestType, InfectionStatus.ClassLibrary.TestType, InfectionStatus.ClassLibrary.TestType, InfectionStatus.ClassLibrary.TestType>>>>>'    UnitTestProject1    D:\F#\Code\InfectionStatus.ClassLibrary\UnitTestProject1\UnitTest1.cs   21  Active

我尝试更改 F# 函数以使用元组而不是柯里化(Currying),但仍然出现编译错误。

将多个参数(非基本类型)从 C# 传递到 F# 的正确方法是什么?

最佳答案

在您的 F# 函数 getHVBStatus 中,您想要再次进行模式匹配的参数之间缺少逗号(在 match 行上)。因此,F# 类型推断将 test1 转换为一个函数,该函数将 test2 和所有其他参数作为参数。

仅从 C# 编译器错误消息很难发现这一点,但如果将鼠标悬停在 test1 上以查看 F# 中的推断类型,您会立即发现有问题。在 match 行添加逗号应该可以解决问题:

let getHVBStatus (test1, test2, test3, test4, test5) =
    match test1, test2, test3, test4, test5 with
    | AntiHBc   (Some(Positive)), 
      AntiHBs   (Some(Positive)), 
      HBeAg     (Some(Positive)), 
      HBsAg     (Some(Positive)), 
      HBVDNA    (Some(Positive))  -> "Normal"
    | _ -> "Elevated"

关于c# - 从 C# 调用 F# 库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58720747/

相关文章:

c# - 从字符串中修剪值并检查数据库

interface - 如何在 F# 中实现返回 void 的接口(interface)成员

f# - Array.Parallel 的“MaxDegreeOfParallelism”?

php - Azure PHP Web 角色,F# 辅助角色 : developing on different machines

f# - 具有可区分联合的主动模式匹配

c# - Google Custom Search .NET API 使用 Fetch 方法编译问题

c# - 按特异性排序通配符匹配列表

c# - 根据下拉选择将 ID 保存到数据库

c# - Identity Server 4 v3.1.2 UserInteraction LoginUrl 不起作用

c# - F# 在管道运算符 aka C# LINQ let 中使用临时变量