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

发布于 2024-08-08 16:39:00 字数 673 浏览 6 评论 0原文

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

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 绑定进行运算符定义,则一切正常:

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

let hw  = foo? world

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

使用 F# 1.9.7.4 @ Visual Studio 2010 Beta2

Can't define (?) operator overload on type:

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'.

All works fine if I use standalone let-binding for operator definition:

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

let hw  = foo? world

But I need to specify op_Dynamic operator directly for type Foo. What's wrong with the first code snippet?

Using F# 1.9.7.4 @ Visual Studio 2010 Beta2

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

亣腦蒛氧 2024-08-15 16:39:00

也许有一个更简单的方法(我会看看),但这会在紧要关头起作用:

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

Perhaps there is an easier way (I'll look), but this will do in a pinch:

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文