2012-11-25 27 views
18

我知道在f#中,我可以將out參數作爲結果元組的成員,當我使用它們從F#開始時,例如,如何創建一個在F#中具有輸出參數的成員

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

我想知道我是怎麼定義的成員有,似乎C#作爲具有out參數簽名。

可以做到這一點嗎?我可以返回一個元組,並在我從C#調用方法時發生相反的過程,例如

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

回答

18

不,你不能返回結果作爲一個元組 - 你需要從函數返回結果之前指派該值將ByRef值。還要注意[<Out>]屬性 - 如果不提​​供該參數,則該參數的作用類似於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" 

如果你想你的方法有一個規範的C#Try簽名(如Int32.TryParse),你應該返回從你的方法bool並傳遞可能解析的Foo背透byref<'T>,像這樣:

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") 
相關問題