如何将静态扩展方法与静态解析的类型参数一起使用?



我想将静态解析的类型参数与我添加到内置类型的一些扩展方法一起使用,例如float32int32,所以我尝试了以下方法:

module Foo =
type System.Single with
static member Bar x = x + 1.0f
let inline bar (x : ^a) =
(^a : (static member Bar : ^a -> ^a) x)
open Foo
[<EntryPoint>]
let main argv =
System.Console.WriteLine (bar 1.0f) (* Compilation fails here *)
0

编译器抱怨The type 'float32' doesn't support the operator 'Bar'.我做错了什么?

静态解析的类型参数不会针对扩展方法解析,因此无法采用这种特定方法。

我建议仔细考虑这是否是你真正需要做的事情,或者你是否可以用不同的方式表达你试图解决的问题。

如果您确定这是您想要的,并且愿意勇敢面对随后的龙,则有一种解决方法涉及使用一些静态方法创建帮助程序类型:

type Ext = Ext
with
static member Bar (ext : Ext, flt : float) = 1.0 + flt
static member Bar (ext : Ext, flt : float32) = 1.0f + flt

然后,可以使用静态解析的类型参数定义一个新函数,如下所示:

let inline bar (x : ^a) =
((^b or ^a) : (static member Bar : ^b * ^a -> ^a) (Ext, x))

然后你可以写:

bar 7.0f
val it : float32 = 8.0f
bar 5.0
val it : float = 6.0

最新更新