异常类型可以通用吗? [英] Can exception types be generic?
问题描述
我尝试了以下操作,这些操作均无效。
I've tried the following, which don't work.
exception MyError<'a> of 'a
exception 'a MyError of 'a
的MyError是否必须使用long形式:
Do I have to use the long form:
type MyError<'a>(value) =
inherit System.Exception()
member this.Value : 'a = value
推荐答案
规范,您必须使用长格式。我没有找到任何解释为什么会这样,但是异常声明的语法看起来像这样(也许也暗示了为什么行为是您所描述的):
According to the specification, you have to use the long form. I didn't find any explanation why that's the case, but the grammar for exception declarations looks like this (and maybe also hints why the behavior is as you described):
exception-defn:=属性 opt 异常 union-type-case-data
exception-defn := attributesopt exception union-type-case-data
union-type-case-data:=
身份 ; (空联盟案例)
标识符 of 类型* ... *类型 (一元联合案例)
ident:未处理的签名 << i"(i-ary联合案例)
union-type-case-data :=
ident (nullary union case)
ident of type * ... * type (n-ary union case)
ident : uncurried-sig (n-ary union case)
这很有趣,因为它表明异常声明比类似类型更像区分联合案例。我想您可以想到一个异常声明...
This is quite interesting, because it suggests that exception declarations are more like discriminated union cases than like types. I guess you can think of an exception declaration...
exception MyExn of int
...作为向标准 System.Exception
类型添加新案例的声明这是一个受歧视的工会)。在这种情况下,您将无法使用通用类型参数:
...as a declaration adding new case to the standard System.Exception
type (if it was a discriminated union). In this case you wouldn't expect to be able to use a generic type parameter:
type System.Exception =
| ...
| MyExn of int
这篇关于异常类型可以通用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!