F #

2012-11-25 6 views
18

içinde bir out parametresi olan bir üye nasıl oluşturabilirim? F # içinde out parametrelerinin F # öğesinden kullandıkları zaman sonuç tuple'ı gibi davranabildiğini biliyorum. Bir out parametresini sahip olarak C# görünen imzaya sahip bir üye tanımlamak nasılF #

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

Bilmek istiyorum olduğunu.

Bunu yapmak mümkün mü? Ve sadece bir tuple döndürebilir ve C# yöntemini çağırdığım zaman zıt işlemi gerçekleştirebilirim.

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

cevap

18

Hayır , bir demet olarak sonuç döndürmez olabilir - işlevinden sonucu dönmeden önce byref değere değer atamanız gerekir. Ayrıca [<Out>] özniteliğine de dikkat edin - eğer bunu bırakırsanız, parametre bir C# ref parametresi gibi davranır.

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" 

Eğer yöntem kanonik C# Try imzayı sahip olmak istiyorsanız (örneğin Int32.TryParse), kendi yönteminden bir bool dönmek ve geçmelidir geri byref<'T> aracılığıyla Foo muhtemelen-ayrıştırılır şöyle:

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")