无法在类型上定义(?)运算符重载:
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
但我需要直接为op_Dynamic
类型指定Foo
运算符。第一个代码段出了什么问题?
使用F# 1.9.7.4
@ Visual Studio 2010 Beta2
答案 0 :(得分:4)
也许有一种更简单的方式(我会看),但这样做会在紧要关头:
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