Sovraccarico dell'operatore di ricerca dinamica F # (?)
-
06-07-2019 - |
Domanda
Impossibile definire il sovraccarico (?) dell'operatore sul tipo:
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'.
Tutto funziona bene se uso un let-binding autonomo per la definizione dell'operatore:
let (?) (foo : Foo) (name : string) = foo.s + name
let hw = foo? world
Ma devo specificare l'operatore op_Dynamic
direttamente per il tipo Foo
. Cosa c'è di sbagliato nel primo frammento di codice?
Uso di F # 1.9.7.4
@ Visual Studio 2010 Beta2
Soluzione
Forse c'è un modo più semplice (guarderò), ma questo farà un pizzico:
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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow