当参数是对象类型时,如何在F#中要求多个接口?

rab*_*ens 6 f# scala

在scala中,我可以要求多个特征,如下所示:

def foo(bar: Foo with Bar): Unit = {
  // code
}
Run Code Online (Sandbox Code Playgroud)

这在F#中也是可能的,还是我必须显式声明一个FooBar继承Foo和接口Bar

Tom*_*cek 10

您可以通过具有'T约束限制'T为实现所需接口的类型的泛型类型来进行指定。

例如,给定以下两个接口:

type IFoo = 
  abstract Foo : int 
type IBar = 
  abstract Bar : int 
Run Code Online (Sandbox Code Playgroud)

我可以编写一个函数,要求'Twhich IFoo和also IBar

let foo<'T when 'T :> IFoo and 'T :> IBar> (foobar:'T) = 
  foobar.Bar + foobar.Foo
Run Code Online (Sandbox Code Playgroud)

现在,我可以创建一个实现两个接口的具体类,并将其传递给我的foo函数:

type A() = 
  interface IFoo with 
    member x.Foo = 10
  interface IBar with 
    member x.Bar = 15

foo (A()) // Type checks and returns 25 
Run Code Online (Sandbox Code Playgroud)