在 scala 中,我可以要求这样的多个特征:
def foo(bar: Foo with Bar): Unit = {
// code
}
这在 F# 中是否也可以,或者我必须明确声明
FooBar
继承 Foo
的接口(interface)和 Bar
?
最佳答案
您可以通过使用泛型类型'T
来指定它。带有限制 'T
的约束到实现所需接口(interface)的类型。
例如,给定以下两个接口(interface):
type IFoo =
abstract Foo : int
type IBar =
abstract Bar : int
我可以编写一个需要
'T
的函数这是IFoo
还有IBar
:let foo<'T when 'T :> IFoo and 'T :> IBar> (foobar:'T) =
foobar.Bar + foobar.Foo
现在我可以创建一个实现这两个接口(interface)的具体类并将它传递给我的
foo
。功能:type A() =
interface IFoo with
member x.Foo = 10
interface IBar with
member x.Bar = 15
foo (A()) // Type checks and returns 25
关于scala - 当参数是对象类型时,如何在 F# 中要求多个接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56687023/