F#函数具有多态(在OO意义上)返回类型

Dan*_*iel 2 f#

是否可以让函数返回多个类型,只要它们共享一个公共基类,而不转换每个返回值?

例如:

[<AbstractClass>]
type A() = 
  abstract Do : unit -> unit

type B() =
  inherit A()
  override x.Do() = ()

type C() =
  inherit A()
  override x.Do() = ()

let getA i : A =
  if i = 0 then new B() else new C() //Error: This expression was expected to have type A but here has type B
Run Code Online (Sandbox Code Playgroud)

Bri*_*ian 6

不,你必须施放:

let getA i : A =
  if i = 0 then upcast new B() else upcast new C()
Run Code Online (Sandbox Code Playgroud)