我正在尝试在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)
Run Code Online (Sandbox Code Playgroud)
不幸的是,我的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
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
这似乎有效:
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
Run Code Online (Sandbox Code Playgroud)