【问题标题】:Generic F# type with non-generic constructor具有非泛型构造函数的泛型 F# 类型
【发布时间】:2011-04-23 20:12:39
【问题描述】:

有没有办法让泛型类型带有创建非泛型实例的无参数构造函数?非编译示例:

type Child<'T>() = class end

type Parent<'T>(c:Child<'T>) =
   new() = Parent(Child<unit>()) // ERROR: This code is less generic than required by 
                                 // its annotations because the explicit type variable
                                 // 'T' could not be generalized. It was constrained to be 'unit'.

我想要一个非泛型值以避免值限制,也因为我想使用 'T 进行重载(例如重载 Parent&lt;int&gt;Parent&lt;bool&gt; 等)。

我认为这可能是不可能的,我需要找到一种不同的方式来建模事物。但也许有人有想法?

【问题讨论】:

    标签: generics f#


    【解决方案1】:

    你想要的都是不可能的——当调用一个泛型对象的构造函数时,调用者总是可以指定他想要的任何类型参数。这类似于调用静态方法——调用者总是可以指定一个类型:

    let a = new Parent<Foo>()
    let b = Parent<Foo>.Bar
    

    Parent&lt;'T&gt; 类型中的构造函数始终返回Parent&lt;'T&gt; 类型的值,因此您无法避免使用'T 类型作为类型签名的一部分。但是,静态方法可以有不同的返回类型。

    也许您可以使用静态方法而不是构造函数?

    type Child<'T>() = class end
    type Parent<'T>(c:Child<'T>) =
        static member New() = Parent(Child<unit>())
    

    然后你可以写:

    let a = Parent.New()
    let b = Parent<Foo>.New() // You can specify type parameter, but it is ignored, 
                              // because return type is always 'Parent<unit>'
    

    【讨论】:

      【解决方案2】:

      老实说,我认为您确实在寻找可选参数。

      type Parent<'T>(?c:Child<'T>) = class 
      
          end
      

      当然这需要他们指定类型,但这有那么糟糕吗?

      let p = Parent<int>()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-16
        • 1970-01-01
        • 2017-03-12
        • 1970-01-01
        相关资源
        最近更新 更多