f# - 如何在F#中创建具有out参数的成员

标签 f# clr

我知道在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/

相关文章:

.net - 从 .NET 生成的 IL 文件有什么用(使用 MSIL assembler-ilasm.exe)?

windows - 在 Windows 上使用 Mono 编译 F# 源代码

c# - 如何添加对动态程序集的引用以编译另一个动态程序集?

c# - 在 C# 中对这种行为的解释是什么

未定义 F# 交互式 CsvProvider

c# - Try-catch 加速我的代码?

c# - 为什么 Property 执行比 Field 或 Method 执行慢?

.net - 状态单子(monad),为什么不是一个元组?

f# - 需要帮助将带有泛型的接口(interface)从 C# 转换为 F#

f# - printfn 没有为国际(非拉丁)字符产生预期的结果