2012-11-25 10 views
18

So che in f # posso trattare i parametri out come membri di una tupla di risultati quando li utilizzo da F #, ad es.Come creare un membro che ha un parametro out in F #

(success, i) = System.Int32.TryParse(myStr) 

Quello che mi piacerebbe sapere è come mi definisco un membro di avere la firma che appare a C# come avere un parametro out.

È possibile farlo? E posso solo restituire una tupla e fare il processo opposto quando chiamo il metodo da C#, ad es.

type Example() = 
    member x.TryParse(s: string, success: bool byref) 
    = (false, Unchecked.defaultof<Example>) 

risposta

18

No, non si può restituire il risultato come una tupla - è necessario assegnare il valore al valore ByRef prima di ritornare il risultato dalla funzione. Nota anche l'attributo [<Out>]: se lo ometti, il parametro si comporta come un parametro C# ref.

open System.Runtime.InteropServices 

type Foo() = 
    static member TryParse (str : string, [<Out>] success : byref<bool>) : Foo = 
     // Manually assign the 'success' value before returning 
     success <- false 

     // Return some result value 
     // TODO 
     raise <| System.NotImplementedException "Foo.TryParse" 

Se si desidera che il metodo per avere una firma canonica C# Try (ad esempio, Int32.TryParse), si dovrebbe restituire un bool dal metodo e passare il possibilmente-analizzati Foo indietro attraverso il byref<'T>, in questo modo:

open System.Runtime.InteropServices 

type Foo() = 
    static member TryParse (str : string, [<Out>] result : byref<Foo>) : bool = 
     // Try to parse the Foo from the string 
     // If successful, assign the parsed Foo to 'result' 
     // TODO 

     // Return a bool indicating whether parsing was successful. 
     // TODO 
     raise <| System.NotImplementedException "Foo.TryParse" 
4
open System.Runtime.InteropServices 

type Test() = 
    member this.TryParse(text : string, [<Out>] success : byref<bool>) : bool = 
     success <- false 
     false 
let ok, res = Test().TryParse("123") 
Problemi correlati