[英]How to require multiple interfaces in F# when a parameter is an object type?
In scala, I can require multiple traits like this: 在scala中,我可以要求多个这样的特征:
def foo(bar: Foo with Bar): Unit = {
// code
}
Is this also possible in F#, or do I have to explicitly declare a FooBar
interface that inherits Foo
and Bar
? 这在F#中是否也可以,或者我是否必须显式声明一个继承Foo
和Bar
的FooBar
接口?
You can specify this by having a generic type 'T
with constraints that restrict 'T
to types that implement the required interfaces. 您可以通过使用泛型类型'T
with constraints 'T
为实现所需接口的类型来指定它。
For example, given the following two interfaces: 例如,给定以下两个接口:
type IFoo =
abstract Foo : int
type IBar =
abstract Bar : int
I can write a function requiring 'T
which is IFoo
and also IBar
: 我可以编写一个需要'T
即IFoo
和IBar
:
let foo<'T when 'T :> IFoo and 'T :> IBar> (foobar:'T) =
foobar.Bar + foobar.Foo
Now I can create a concrete class implementing both interfaces and pass it to my foo
function: 现在我可以创建一个实现两个接口的具体类,并将其传递给我的foo
函数:
type A() =
interface IFoo with
member x.Foo = 10
interface IBar with
member x.Bar = 15
foo (A()) // Type checks and returns 25
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.