当我尝试创建一些类时
type MyType () =
let func<'T> () = ()
编译器说有一个错误:
显式类型参数只能用于模块或成员绑定
但是MSDN说:
模块级别、类型或计算表达式中的 let 绑定可以具有显式类型参数。表达式中的 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-declopt
class-function-or-value-defnsopt
type-defn-elements
and class-or-value-defn is defined as:
class-function-or-value-defn := attributesopt
static
optlet
rec
opt 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-defnsopt argument-pats return-typeopt = expr
要添加到 Tomas 的答案,如果您需要类型参数但没有该类型的值,则可以使用带有幻像类型参数的类型。例如:
open System
type Foo() =
member x.PrintType<'T> () = printfn "%s" typeof<'T>.Name
type TypeParameter<'a> = TP
let foo = Foo ()
let callFoo (typeParameter : TypeParameter<'a>) =
foo.PrintType<'a> ()
callFoo (TP : TypeParameter<string>)
callFoo (TP : TypeParameter<DateTime>)