【发布时间】:2020-02-12 09:59:37
【问题描述】:
我正在使用下面的代码
// Neat method of finding the TryParse method for any type that supports it.
// See https://stackoverflow.com/a/33161245/158285
let inline tryParseWithDefault (defaultVal:'a) text : ^a when ^a : (static member TryParse : string * ^a byref -> bool) =
let r = ref defaultVal
if (^a : (static member TryParse: string * ^a byref -> bool) (text, &r.contents))
then !r
else defaultVal
但我注意到类型约束
^a : (static member TryParse : string * ^a byref -> bool
使用两次。有没有办法做到以下几点
constraint Parsable a = ( a : ^a : (static member TryParse : string * ^a byref -> bool)
并像使用 Parsable 一样
// Neat method of finding the TryParse method for any type that supports it.
// See https://stackoverflow.com/a/33161245/158285
let inline tryParseWithDefault (defaultVal:'a) text : Parsable =
let r = ref defaultVal
if (^a : (Parsable) (text, &r.contents))
then !r
else defaultVal
【问题讨论】:
标签: f# type-constraints