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

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 绑定(bind),一切正常:
let (?) (foo : Foo) (name : string) = foo.s + name

let hw  = foo? world

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

使用 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

关于dynamic - F# 动态查找运算符 (?) 重载,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1621250/

10-17 00:47