F#中的静态解析字符串转换函数 [英] Statically resolved string conversion function in F#
本文介绍了F#中的静态解析字符串转换函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在F#中创建一个函数,该函数会将某些类型转换为字符串,但不能将其他类型转换为字符串.目的是使得可以传递基元,而不会偶然传递复杂的对象.这是我到目前为止的内容:
I'm trying to create a function in F# that will convert certain types to a string, but not others. The objective is so that a primitive can be passed but a complex object cannot be passed by accident. Here's what I have so far:
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
函数收到以下编译时错误:
Unfortunately, my conv
function gets the following compile-time error:
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
这篇关于F#中的静态解析字符串转换函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文