【发布时间】:2020-08-27 23:50:44
【问题描述】:
我有一个泛型类,其默认构造函数接受泛型类型的参数。在创建第二个非泛型构造函数时,F# 编译器会抱怨 This type parameter has been used in a way that constrains it to always be 'EmptyType',我根本不理解这个错误。为什么会受到约束?第二个构造函数与第一个构造函数的泛型属性有什么关系?
此示例显示了错误(可在 F# Playground 中重现)。请注意,只需注释第二个构造函数(第 9 行),即可解决编译问题:
type MyInterface = interface end
type EmptyType() = interface MyInterface
type RealType(v: int) =
member this.Value = v
interface MyInterface
type MyType<'T when 'T :> MyInterface>(element: 'T) =
new() = MyType(EmptyType())
member this.X = 0
[<EntryPoint>]
let main _ =
//let a = MyType() //empty constructor, 'T is EmptyType
let b = MyType(RealType(0)) //doesnt work because compiler says 'T is always EmptyType? what?
0
【问题讨论】: