如何使用重载的显式转换运算符? [英] How to use overloaded explicit conversion operators?
问题描述
我在C#中定义了这样的类型:
I have a type defined in C# like this:
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#中,如果我想长时间创建它,我发现的唯一方法是:
In F# if I want to create it from a long, the only way I found is:
let l = F.op_Explicit 3L
我尝试创建一个内联函数以使其变得更好:
I tried creating an inline function to make this nicer:
let inline f a = F.op_Explicit a
但这无法编译.我还尝试了成员约束:
But this doesn't compile. I also tried with a member constraint:
let inline f (x:^a) = (F: (static member op_Explicit : ^a -> F) x)
那也不会编译.
是否可以定义一个函数或运算符来选择正确的重载?
Is it possible to define a function or operator to choose the right overload?
顺便说一句,它确实可以在相反的方向上很好地工作:
On a side note, it does work nicely in the opposite direction:
let f = someF |> int64 // calls the right conversion operator
推荐答案
在单个具体类型上具有成员约束是无效的.但是,这可能对您有用:
It's not valid to have a member constraint on a single concrete type; however, this might work for you:
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)
,该类型无法使用手动注释任何值!
This has the more general type f : ^a -> F when ( ^a or F) : (static member op_Explicit : ^a -> F)
, which is a type that is impossible to manually annotate any value with!
这篇关于如何使用重载的显式转换运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!