F# 中静态解析的字符串转换函数

2024-01-03

我正在尝试在 F# 中创建一个函数,将某些类型转换为字符串,但不会将其他类型转换为字符串。目标是可以传递基元,但不能意外传递复杂对象。这是我到目前为止所拥有的:

type Conversions =
    static member Convert (value:int) =
        value.ToString()
    static member Convert (value:bool) =
        value.ToString()

let inline convHelper< ^t, ^v when ^t : (static member Convert : ^v -> string) > (value:^v) =
    ( ^t : (static member Convert : ^v -> string) (value))

let inline conv (value:^v) = convHelper<Conversions, ^v>(value)

不幸的是,我的conv函数出现以下编译时错误:

A unique overload for method 'Convert' could not be determined based on type information
prior to this program point. A type annotation may be needed. Candidates: 
    static member Conversions.Convert : value:bool -> string, 
    static member Conversions.Convert : value:int -> string

我究竟做错了什么?


这似乎有效:

type Conversions = Conversions with 
    static member ($) (Conversions, value: int) = value.ToString()
    static member ($) (Conversions, value: bool) = value.ToString()

let inline conv value = Conversions $ value

conv 1 |> ignore
conv true |> ignore
conv "foo" |> ignore //won't compile
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

F# 中静态解析的字符串转换函数 的相关文章

随机推荐