generics - 如何访问在 F# 中声明为泛型参数的类型的静态成员

标签 generics f# constraints

我想在 F# 中创建一个基类型,这将允许我通过预定义约束简化其他类型的创建,即。限制为非负整数等。 我创建了以下基本类型,它打算使用作为泛型参数提供的验证器类型的静态成员,希望我能够引用其静态“条件”成员 - 不幸的是,我似乎无法在任何地方引用泛型 ^tf类型主体,更不用说它的静态成员了。

  type Constrained<^tf when ^tf:(static member Condition: 'tv->bool)> (value : int) =
     static member Create (v) =             
        match ^tf.Condition v with
        | true -> Some ( Constrained(v) )
        | _ -> None

我是 F# 新手,所以我不确定我想要做的事情是否可以在 F# 中真正实现...

最佳答案

再次阅读您的问题后,我认为您想要编写如下代码:

type T = T with
    static member Condition (x) = x > 0

type Constrained< ^tf when ^tf:(static member Condition: int->bool)> (value : int) =
    static member inline Create (v) =             
        match (^tf : (static member Condition : int->bool) v) with
        | true -> Some ( Constrained(v) )
        | _    -> None


let x:Constrained<T> option = Constrained<T>.Create(1)

但不确定这会给你带来什么。

关于generics - 如何访问在 F# 中声明为泛型参数的类型的静态成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46585604/

相关文章:

matlab - 使用 fmincon 进行约束最小化

generics - 如何在 Kotlin 中获取泛型参数类

swift - 为什么我的简单协议(protocol)只能用作通用约束?

f# - 在 F# 中使用 Array.map 省略数组的第一个元素

f# - 为什么这个计量单位限制为 1?

f# - Mono 编译器中的错误 : Files in libraries or multiple-file applications must begin with a namespace or module declaration

Excel 求解器忽略 VBA 中的约束

java - 对于泛型和原始类型都是可迭代的

c# - 继承 .NET 的通用 Controller 类

sql-server - SQL Server 约束允许 "two unique"值