c# - 在 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# 的空 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;
}
}
推荐阅读
- postgresql - 使用 heroku pg:pull 时 pg_dump 出错
- java - 在非 SDK 接口上访问隐藏方法 logcat 警告和限制
- excel - 如何在 BIRT excel 报告中呈现大量行(50k 的顺序)?
- java - 连接问题(JTextfield、Jtable、sql 数据库)
- mysql - Laravel 根据 json 的范围获取属性值
- firebase - 使用 Arduino 发送 Firebase 消息时出错
- delphi - Delphi IBX异常处理中的Firebird 3.x错误“尝试执行未准备好的动态SQL语句”?
- java - 识别来电者android并在toast中显示
- c - 如何在while循环中找到最大值和最小值 - c
- java - 使用两个线程读取文件时抛出 java.nio.BufferOverflowException