类中let绑定中的显式类型参数 [英] Explicit type parameters in let bindings in classes
问题描述
当我尝试创建类似的类
type MyType () =
let func<'T> () = ()
编译器说有错误:
显式类型参数只能在模块或成员绑定上使用
Explicit type parameters may only be used on module or member bindings
但是 MSDN 说:
在模块级别,类型或计算表达式中的let绑定可以具有显式类型参数.在表达式中(例如在函数定义中)的let绑定不能具有类型参数.
A let binding at the module level, in a type, or in a computation expression can have explicit type parameters. A let binding in an expression, such as within a function definition, cannot have type parameters.
为什么文档和编译器说的不同?
Why documentation and compiler say different things?
推荐答案
这似乎是对类内 let
绑定的语法限制.但是,您仍然可以定义通用的局部函数,只需要在类型注释中指定类型参数即可:
This appears to be a syntactic restriction on let
bindings inside a class. However, you can still define a generic local function, you just have to specify the type parameters in type annotations:
type MyType () =
let func (x : 'T) : 'T = x
我不认为这在语法上明确地在语法上是禁止的,因为该规范说类定义具有以下结构:
I do not think this is explicitly syntactically forbidden by the specification, because the specification says that a class definition has the following structure:
type type-name patopt as-defnopt =
class-inherits-decl opt
class-function-or-value-defns opt
类型定义元素
type type-name patopt as-defnopt =
class-inherits-declopt
class-function-or-value-defnsopt
type-defn-elements
和 class-or-value-defn 定义为:
class-function-or-value-defn:=属性 opt
静态
optlet
rec
opt 函数或值定义
class-function-or-value-defn := attributesopt
static
optlet
rec
opt function-or-value-defns
其中 function-or-value-defns 可能是带有显式类型参数的函数定义:
where function-or-value-defns may be a function definition with explicit type parameters:
function-defn:=
inline
optaccess
opt ident-or-op typar-defns opt 参数-pats return-typeopt = expr
function-defn :=
inline
optaccess
opt ident-or-op typar-defnsopt argument-pats return-typeopt = expr
这篇关于类中let绑定中的显式类型参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!