首页 文章

类中let绑定的显式类型参数

提问于
浏览
7

当我尝试创建类似的类时

type MyType () =
    let func<'T> () = ()

编译器说有错误:

显式类型参数只能用于模块或成员绑定

MSDN说:

模块级别,类型或计算表达式中的let绑定可以具有显式类型参数 . 表达式中的let绑定(例如在函数定义中)不能具有类型参数 .

为什么文档和编译器说不同的东西?

2 回答

  • 5

    这似乎是对类中 let 绑定的语法限制 . 但是,您仍然可以定义通用本地函数,只需在类型注释中指定类型参数:

    type MyType () =
       let func (x : 'T) : 'T = x
    

    我不认为规范明确禁止这种语法,因为规范说类定义具有以下结构:

    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:= attributesopt staticopt let recopt function-or-value-defns

    其中function-or-value-defns可以是具有显式类型参数的函数定义:

    function-defn:= inlineopt accessopt ident-or-op typar-defnsopt参数-pats return-typeopt = expr

  • 2

    要添加到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>)
    

相关问题