这是一个简单的类型层次结构.
type Parent() = class end
type Child() = inherit Parent()
Run Code Online (Sandbox Code Playgroud)
我想将类型的函数('x -> Child)视为('x -> Parent):
let f (x: 'x): Child = new Child()
let g: ('x -> Parent) = f // error
Run Code Online (Sandbox Code Playgroud)
但是最后一次分配失败了The type 'Parent' does not match the type 'Child'.有没有办法让这项工作?
您可以使用upcast运算符(:>)使其工作:
type Parent () = class end
type Child () = inherit Parent ()
let f x = Child () // val f : x:'a -> Child
let g x = f x :> Parent // val g : x:'a -> Parent
Run Code Online (Sandbox Code Playgroud)