代码之家  ›  专栏  ›  技术社区  ›  Chechy Levas

有没有办法将泛型类型约束为一组类型的成员?

  •  0
  • Chechy Levas  · 技术社区  · 5 年前

    type RecordPath<'a,'b> = {
        Get: 'a -> 'b
        Path:string
    }
    

    我想约束 'b 成为可以在关系数据库列中自然表示的类型集的成员( int string ; DateTime

    我可以使用一个类,而不是一个带有私有构造函数和一些静态创建者方法的记录,这些方法只适合我所关心的类型。但我想知道是否有一种方法可以用唱片做到这一点。

    我还考虑过用这样的东西扩展我想要允许的类型

    type String with static member CanBeUsedInRecordPath = true
    

    RecordPath ,但从技术上讲,有人决定扩展我不想用这种扩展方法支持的某种类型是可能的(尽管不太可能)。

    那么,在F#中,具有私有构造函数的类是实现这一点的唯一方法吗?

    0 回复  |  直到 5 年前
        1
  •  2
  •   Chechy Levas    5 年前

    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"}
    

    在接受这个答案之前,我会稍等片刻,以防有人想出更好的方法。