开发者

F# function with polymorphic (in the OO sense) return type

Is it possible to have a function return multiple types as long as they share a common base class, without casting each return value?

For example:

[<AbstractClass>开发者_JAVA百科;]
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


No, you have to cast:

let getA i : A =
  if i = 0 then upcast new B() else upcast new C()


I believed you could use generics with constraints to define a return type of 'a when a :> SomeType but I've now got to fire up VS to check.

Edit: nope.. curses... you'll have to cast.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜