我有以下记录
type RecordPath<'a,'b> = {
Get: 'a -> 'b
Path:string
}
我想将'b
约束为一组类型的成员,这些类型可以自然地在关系数据库列中表示(int
;string
;DateTime
;等等(。
我可以使用一个类,而不是一个带有私有构造函数和一些静态创建者方法的记录,这些方法只适合我关心的类型。但我想知道是否有办法用唱片做到这一点。
我还考虑过用这种来扩展我想要允许的类型
type String with static member CanBeUsedInRecordPath = true
然后对在RecordPath
上运行的所有函数使用SRTP,但从技术上讲,有人决定用这种扩展方法扩展一些我不想支持的类型是可能的(尽管不太可能(。
那么,在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"}
我会等一段时间再接受这个答案,以防有人想出更好的方法。