我知道在f#中我可以将out参数视为结果元组的成员,当我从F#中使用它们时,例如
(success, i) = System.Int32.TryParse(myStr)
Run Code Online (Sandbox Code Playgroud)
我想知道的是我如何定义一个成员,使C#中的签名看起来像一个out参数.
是否有可能做到这一点?我可以只返回一个元组,并且当我从C#调用该方法时会发生相反的过程,例如
type Example() =
member x.TryParse(s: string, success: bool byref)
= (false, Unchecked.defaultof<Example>)
Run Code Online (Sandbox Code Playgroud)
Jac*_* P. 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"
Run Code Online (Sandbox Code Playgroud)
如果你希望你的方法有一个规范的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"
Run Code Online (Sandbox Code Playgroud)
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")
Run Code Online (Sandbox Code Playgroud)