我在C#中定义了这样的类型:
struct F {
public static explicit operator F(long value) {}
public static explicit operator long(F value) {}
public static explicit operator F(double value) {}
public static explicit operator double(F value) {}
// more conversion operators
}
在F#中,如果我想长时间创建它,则发现的唯一方法是:
let l = F.op_Explicit 3L
我尝试创建一个内联函数来使它更好:
let inline f a = F.op_Explicit a
但这无法编译。我还尝试了成员约束:
let inline f (x:^a) = (F: (static member op_Explicit : ^a -> F) x)
而且也不编译。
是否可以定义一个函数或运算符来选择正确的重载?
顺便说一句,它确实在相反的方向上很好地工作:
let f = someF |> int64 // calls the right conversion operator
对单个具体类型具有成员约束是无效的。但是,这可能对您有用:
let inline f (x:^a) : F =
let inline g x = ((^b or ^c):(static member op_Explicit : ^b -> ^c) x)
g x
它具有更通用的类型f : ^a -> F when ( ^a or F) : (static member op_Explicit : ^a -> F)
,该类型是无法使用手动注释任何值的类型!
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句