我知道在f#中,当我从F#中使用out
参数作为结果元组的成员时,例如
(success, i) = System.Int32.TryParse(myStr)
我想知道的是如何定义一个成员以使签名在C#中看起来像具有
out
参数。是否有可能做到这一点?当我从C#调用方法时,例如我可以只返回一个元组并进行相反的处理吗?
type Example() =
member x.TryParse(s: string, success: bool byref)
= (false, Unchecked.defaultof<Example>)
最佳答案
不,您不能将结果作为元组返回-您需要在从函数返回结果之前将值分配给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"
关于f# - 如何在F#中创建具有out参数的成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13547146/