dynamic - F# 动态查找运算符(?)重载

标签 dynamic f# operator-overloading

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

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

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

相关文章:

C# 4.0,检测方法是否缺失

python - 动态创建类实例的最有效方法是什么?

.net - 在多线程环境中使用TraceSource

operator-overloading - 如何在Rust中实现惯用运算符重载值和引用?

c++ - 实现 C++ 后缀增量运算符

c++ - 如何使用 getProcAddress() 而不进行类型转换?

loops - 动态 WHERE 子句 IN LOOP AT 语句

f# - 如何从 xml 文件读取属性值 - FAKE F#MAKE

F# 管道和函数应用程序之间的神秘差异

c++ - 运算符重载