在玩了一些 F# 成员约束功能和编写这样的函数之后:
let inline parse< ^a when ^a : (static member Parse: string -> ^a) > s =
(^a: (static member Parse: string -> ^a) s)
这工作得很好:
let xs = [ "123"; "456"; "999" ] |> List.map parse<int>
我正在尝试编写其他 func tryParse
,它使用静态方法TryParse
并将解析结果包装成'a option
类型,以便在 F# 中获得更好的支持。像这样的东西不会编译:
let inline tryParse s =
let mutable x = Unchecked.defaultof< ^a>
if (^a: (static member TryParse: string * ^a byref -> bool) (s, &x))
then Some x else None
错误是:
错误 FS0001:此表达式的类型应为 byref<'a> 但此处的类型为 'a ref
F# ref
-cells 也不起作用:
let inline tryParse s =
let x = ref Unchecked.defaultof< ^a>
if (^a: (static member TryParse: string * ^a byref -> bool) (s, x))
then Some x else None
我究竟做错了什么?