支持成员约束的静态扩展方法
我需要实现一个静态扩展方法,支持对一些基本基元类型(如整数、浮点数等)的成员约束。这是我的有符号整数代码:
module MyOperators =
let inline foo (x : ^T) = (^T : (static member Foo : ^T -> int) (x))
type System.Int32 with
static member Foo(x : Int32) = 7 // static extension
测试代码:
open MyOperators
let x = foo 5 // x should be 7
但编译器抱怨错误:
类型“System.Int32”不 支持任何名为“Foo”的运算符
我在这里缺少什么?谢谢!
I need to implement a static extension method supporting member constraints on some basic primitive types like integers, floats, etc. Here's my code for signed integers:
module MyOperators =
let inline foo (x : ^T) = (^T : (static member Foo : ^T -> int) (x))
type System.Int32 with
static member Foo(x : Int32) = 7 // static extension
Test code:
open MyOperators
let x = foo 5 // x should be 7
But compiler complains with error:
The type 'System.Int32' does not
support any operators named 'Foo'
What am I missing here? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
F# 中的静态成员约束永远不会找到“扩展方法”,它们只能看到类型上的内部方法(以及 F# 语言规范中提到的一些特殊情况)。
也许你可以使用方法重载来代替?你的最终目标是什么?
Static member constraints in F# never find 'extension methods', they can only see intrinsic methods on types (and a few special cases called out in the F# language spec).
Perhaps you can use method overloading instead? What is your ultimate goal?
F# 的静态类型约束不适用于扩展方法。扩展方法无法在编译时静态检查,即使如此,您也可以对 Int32::Foo 有多个定义(取决于您导入的命名空间)。
不幸的是,要解决您的问题,您可能不得不求助于使用反射。
F#'s static type constraints don't work with extension methods. Extension methods cannot statically be checked at compile time, and even so, you can have multiple definitions for Int32::Foo (depending on which namespace you imported).
Unfortunately, to solve your problem you might have to resort to using reflection.