簡體   English   中英

從 C# 調用 F# 庫

[英]Invoking an F# library from C#

我有一個 C# 使用的 F# class 庫。

F# 庫有兩種類型和一種簡單的 function,我想從我的 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# function 更改為使用元組而不是currying,但仍然出現編譯錯誤。

將多個 arguments(非原始類型)從 C# 傳遞到 F# 的正確方法是什么?

在您的 F# function getHVBStatus中,您想要再次進行模式匹配的參數之間缺少逗號(在match行上)。 結果,F# 類型推理將test1轉換為 function,它將test2和所有其他參數作為 arguments。

僅從 C# 編譯器錯誤消息中很難發現這一點,但如果您在test1上查看 hover 以查看 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"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM