2012-11-25 9 views
18

Wiem, że w f # mogę traktować parametry out jako członków krotki wynikowej, gdy używam ich z F #, np.Jak utworzyć element, który ma parametr out w F #

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

Co chciałbym wiedzieć, w jaki sposób zdefiniować element mieć podpis, który wydaje się C# jako mające parametr out.

Czy można to zrobić? I mogę po prostu zwrócić krotkę i mieć przeciwny proces, gdy wywołuję metodę z C#, np.

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

Odpowiedz

18

Nie, nie można zwrócić wynik jak krotki - trzeba przypisać wartość do wartości ByRef przed zwróceniem wynik z funkcji. Zwróć także uwagę na atrybut [<Out>] - jeśli go nie wybierzesz, parametr będzie podobny do parametru 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" 

Jeśli chcesz, aby Twój sposób mieć kanoniczny C# Try podpisu (np Int32.TryParse), należy zwrócić bool od wybranej metody i przekazać możliwie-analizowany Foo powrotem przez byref<'T>, tak:

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") 
Powiązane problemy