具有非泛型构造函数的泛型F#类型
问题描述:
是否有某种方法可以使用无参数构造函数来创建非泛型实例的泛型类型?非编译例如:具有非泛型构造函数的泛型F#类型
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<int>
与Parent<bool>
等重载)。
我认为这可能是不可能的,我需要找到一种不同的方式来模拟事物。但也许有人有一个想法?
答
你想要什么是不可能的 - 调用通用对象的构造函数时,主叫方可以始终指定任何他想要的类型参数。这类似于调用一个静态方法 - 调用者总是可以指定类型:
let a = new Parent<Foo>()
let b = Parent<Foo>.Bar
在类型Parent<'T>
的构造函数总是返回Parent<'T>
类型的值,所以你不能避免使用类型'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>'
答
太老实了我觉得你真的在寻找一个可选参数。
type Parent<'T>(?c:Child<'T>) = class
end
当然,这需要他们指定的类型,但是那么糟糕?
let p = Parent<int>()