无法在类型上定义(?)运算符重载:

type Foo =
     val s : string
     new(s) = { s = s }
     static member (?) (foo : Foo, name : string) = foo.s + name

let foo = Foo("hello, ")
let hw  = foo? world

// error FS0043: The member or object constructor 'op_Dynamic'
// takes 2 argument(s) but is here given 1. The required signature
// is 'static member Foo.( ? ) : foo:Foo * name:string -> string'.

如果我使用独立的let-binding进行运算符定义,那么一切正常:

let (?) (foo : Foo) (name : string) = foo.s + name

let hw  = foo? world

但我需要直接为 Foo 指定 op_Dynamic 运算符。第一个代码段出了什么问题?

使用 F#1.9.7.4 @ Visual Studio 2010 Beta2

有帮助吗?

解决方案

也许有一种更简单的方式(我会看),但这样做会在紧要关头:

type Foo =     
    val s : string     
    new(s) = { s = s }     
    static member (?)(foo : Foo, name : string) = 
        foo.s + name

let inline (?) (o:^T) (prop:string) : ^U =
    (^T : (static member (?) : ^T * string -> ^U)(o,prop))

let foo = Foo("hello, ")
let hw  = foo ? world 
printfn "%s" hw
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top