假设我在C#中有一个带有重载的隐式和显式运算符的类:
public static implicit operator CSClass(int a) => ...;
public static explicit operator int(CSClass a) => ...;
我将此项目编译为类库。
现在,在F#中,我可以添加用于隐式转换的运算符并使用它:
#r @"C:\path\to.dll"
open Some.Namespace.ToMyClass
let inline (!>) (x:^a) : ^b = ((^a or ^b) : (static member op_Implicit : ^a -> ^b) x)
let a : CSClass = !> 5
但是,如何在F#中执行显式的重载转换?(CSClass
至int
)
据我了解,F#通常不进行显式转换。相反,您将只使用一个函数。例如,如果您有一个,char
并且想要int
在C#中将其显式转换为,则可以编写:
char theChar = 'A';
int convertedChar = (int)theChar;
在F#中,int
运算符(函数)用于相同目的:
let theChar = 'A'
let convertedChar = int theChar;
因此,惯用的转换方式如下所示:
module Some.Namespace.MyClass
let toInt (x : MyClass) = [...]
您可以这样使用它:
let convertedMyClass = MyClass.toInt myClass
也可以通过管道传递:
funcReturningMyClass x y
|> MyClass.toInt
|> printfn "%d"
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句