gpt4 book ai didi

generics - 有没有办法将泛型类型限制为一组类型的成员?

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

我有以下记录

type RecordPath<'a,'b> = {
Get: 'a -> 'b
Path:string
}
我要约束 'b成为可以在关系数据库列中自然表示的类型集的成员( intstringDateTime;等)。
我可以使用一个类而不是一个带有私有(private)构造函数的记录和一些只满足我关心的类型的静态创建者方法。但我想知道是否有办法通过记录来做到这一点。
我还考虑过用这样的方式扩展我想要允许的类型
type String with static member CanBeUsedInRecordPath = true
然后将 SRTP 用于在 RecordPath 上运行的所有功能。 ,但是从技术上讲,有人决定扩展某种我不想使用该扩展方法支持的类型在技术上是可能的(尽管不太可能)。
那么具有私有(private)构造函数的类是在 F# 中执行此操作的唯一方法吗?

最佳答案

以下似乎满足我的要求。

module RecordPath =
type RecordPath<'a, 'b> = private {
Get: 'a -> 'b
Path:string
}
with
static member Create (f: 'a -> string) = {Get = f; Path = "not important for this demo"}
static member Create (f: 'a -> int) = {Get = f; Path = "not important for this demo"}
static member Create (f: 'a -> DateTime) = {Get = f; Path = "not important for this demo"}
在接受这个作为答案之前,我会稍等片刻,以防有人想出更好的方法。

关于generics - 有没有办法将泛型类型限制为一组类型的成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64416756/

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