【问题标题】:Is there a way of constraining a generic type to be a member of a set of types?有没有办法将泛型类型限制为一组类型的成员?
【发布时间】:2020-10-18 18:18:51
【问题描述】:

我有以下记录

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

我想将 'b 限制为可以在关系数据库列中自然表示的类型集的成员(intstringDateTime;等)。

我可以使用类而不是带有私有构造函数的记录和一些仅满足我关心的类型的静态创建者方法。但我想知道是否有办法通过记录来做到这一点。

我还考虑过用类似的方式扩展我想要允许的类型

type String with static member CanBeUsedInRecordPath = true

然后将 SRTP 用于在 RecordPath 上运行的所有功能,但技术上可能(尽管不太可能)有人决定使用该扩展方法扩展我不想支持的某种类型。

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

【问题讨论】:

    标签: generics f#


    【解决方案1】:

    以下似乎满足我的要求。

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

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

    【讨论】:

    • 这正是我在看到你的问题和看到你的答案之前要建议的:-)。我认为这可能是最好的方法。
    • 我有一个类似的场景,我做了完全相同的事情。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-26
    • 1970-01-01
    • 2022-06-21
    • 1970-01-01
    相关资源
    最近更新 更多