gpt4 book ai didi

f# - 支持成员约束的静态扩展方法

转载 作者:行者123 更新时间:2023-12-04 17:58:27 24 4
gpt4 key购买 nike

我需要实现一个静态扩展方法来支持对一些基本原始类型(如整数、浮点数等)的成员约束。这是我的有符号整数代码:

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

但是编译器提示错误:

The type 'System.Int32' does not support any operators named 'Foo'



我在这里缺少什么?谢谢!

最佳答案

F# 中的静态成员约束永远找不到“扩展方法”,它们只能看到类型的内部方法(以及 F# 语言规范中调用的一些特殊情况)。

也许您可以改用方法重载?你的最终目标是什么?

关于f# - 支持成员约束的静态扩展方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3681142/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com