首页 > 解决方案 > 在 C# 中为 F# 中定义的类型进行模式匹配

问题描述

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

type ConstObj = {value:int;}

type Instruction =
      | CONST of ConstObj
      | HALT

我可以成功地对 CONST 指令进行模式匹配,但无法匹配 HALT,因为编译器在编译期间抛出错误,提示“CS0426 类型名称‘HALT’不存在于类型‘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

解决方案


这个答案完全是从这篇博文中偷来的。

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;
    }
}

推荐阅读