当我尝试创建类似的类时
type MyType () =
let func<'T> () = ()
Run Code Online (Sandbox Code Playgroud)
编译器说有错误:
显式类型参数只能用于模块或成员绑定
但是MSDN说:
模块级别,类型或计算表达式中的let绑定可以具有显式类型参数.表达式中的let绑定(例如在函数定义中)不能具有类型参数.
为什么文档和编译器说不同的东西?
这似乎是对let类中绑定的语法限制.但是,您仍然可以定义通用本地函数,只需在类型注释中指定类型参数:
type MyType () =
let func (x : 'T) : 'T = x
Run Code Online (Sandbox Code Playgroud)
我不认为规范明确禁止这种语法,因为规范说类定义具有以下结构:
type type-name patopt as-defnopt =
class-inherits-decl opt
class-function-or-value-defns opt
type-defn-elements
和class-or-value-defn定义为:
class-function-or-value-defn:= attributes opt
staticoptletrecopt function-or-value-defns
其中function-or-value-defns可以是具有显式类型参数的函数定义:
function-defn:=
inlineoptaccessopt ident-or-op typar-defns opt argument-pats return-typeopt = expr
要添加到托马斯的答案,如果您需要类型参数但没有该类型的值,您可以使用带有幻像类型参数的类型。例如:
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>)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
581 次 |
| 最近记录: |