【发布时间】:2011-02-17 18:45:37
【问题描述】:
我正在尝试对其定义中的异常进行模式匹配。是否可以使用 F# 的异常语法,或者我必须继承 Exception?
这是我期望的工作:
exception CoordErr of int * int
with
override this.Message =
let CoordErr(x, y) = this
sprintf "(%i %i)" x y //ERROR
但会产生错误:
未定义值或构造函数“x”
未定义值或构造函数“y”
编辑
我也尝试添加括号:
let (CoordErr(x, y)) = this
但这给出了错误:
这个表达式应该有 exn 类型,但这里有 CoordErr 类型
更新
以下方法可行,但并不理想:
exception CoordErr of int * int
with
override this.Message =
sprintf "(%i %i)" this.Data0 this.Data1
还有其他方法吗?
更新 2
从 kvb 的回答中得到提示,我想我可以执行以下操作来吞下 incomplete matches 警告:
exception CoordErr of int * int
with
override this.Message =
match this :> exn with
| CoordErr(x, y) -> sprintf "(%i %i)" x y
| _ -> Unchecked.defaultof<_>
【问题讨论】:
-
我会把它从
Unchecked.defaultof<_>改成failwith "impossible"
标签: exception f# pattern-matching