【问题标题】:pattern matching in C# for type defined in F#在 C# 中为 F# 中定义的类型进行模式匹配
【发布时间】:2021-03-08 04:48:02
【问题描述】:

我已经在 F# 中声明了一个类型,现在我想在 C# 中使用它。类型定义为:

type ConstObj = {value:int;}

type Instruction =
      | CONST of ConstObj
      | HALT

我可以成功地对 CONST 指令进行模式匹配,但无法匹配 HALT,因为编译器在编译期间抛出错误,提示“CS0426 The type name 'HALT' does not exist in the type 'Types.Instruction'”

   private void Eval(Instruction instruction) {
        switch (instruction) {
            case Instruction.CONST c:
                break;
            case Instruction.HALT h:
                break;
            default:
                break;
        }
    }

但是相同的类型可以在 F# 中成功进行模式匹配:

  let matcher x = 
      match x with
      | Instruction.CONST{value=v;} ->
            printfn "Const instruction. Value is %i" v 
      | Instruction.HALT ->
          printfn "HALT instruction" 

有什么想法吗?

【问题讨论】:

    标签: c# f# pattern-matching


    【解决方案1】:

    这个答案完全是从this blog post偷来的。

    C# 无法对来自 F# 的空 DU 案例进行模式匹配。一些可能的解决方法:

    type Record = { Name: string; Age: int }
    
    type Abc =
        | A
        | B of double
        | C of Record
    
    void HandleAbc(Abc abc)
    {
        switch (abc)
        {
            // Option 1:
            case var x when x.IsA:
                Console.WriteLine("A");
                break;
            // Option 2:
            case var x when x == Abc.A:
                Console.WriteLine("A");
                break;
        }
    
        switch (abc.Tag)
        {
            // Option 3:
            case abc.Tags.A:
                Console.WriteLine("A");
                break;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多