考虑以下使用 F# 4.0、.NET 4.6 的代码片段:
type X<'T> = Y of 'T
type XS = X<string>
type XI = X<int>
type X<'T when 'T :> string> with
static member X = 2
static member take (s: 'T) = s
[<CompilationRepresentation(CompilationRepresentationFlags.ModuleSuffix)>]
module XS =
let foo = 10
let create s = XS.Y s
let test = XI.take 2 // expected only string allowed, XI.take should not exist
我希望类型扩展type X<'T when 'T :> string> with
得到尊重(在这种情况下,这意味着错误,因为string
是密封的,或者限制'T
为 be string
),或者引发语法错误。
更重要的是,我也可以使用以下语法,这将是正常类型定义中的语法错误(没有with
):
type X<'T> when 'T :> string with
static member X = 2
static member take (s: 'T) = s
我的猜测是,扩展上的约束被简单地忽略了。这是设计使然吗?或者它应该工作,如果是这样,如何?
当我尝试使用类型扩展并想知道我是否可以创建一组仅适用于特定具体类型或进一步受限的具体类型的特定方法时,我想到了这一切(这也可以通过继承来完成,我知道)。