简体   繁体   English

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

[英]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#中是否也可以,或者我是否必须显式声明一个继承FooBarFooBar接口?

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 : 我可以编写一个需要'TIFooIBar

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.

相关问题 将自定义类型从 F# 转换为 Scala - Translating custom type from F# to Scala scala-如何在需要时完全忽略对象的类型参数 - scala - How to completely ignore an object's type parameter when needed scala特征之间如何要求相同的参数类型? - How to require the same parameter type between scala traits? 传递到Scala中的另一个类时,对象的数据类型是什么? 或如何将对象类型作为参数传递给另一个类? - what is the data type of object when passing to another class in scala ? or how to pass an object type as a parameter to another class? F#vs Scala-为什么我需要告诉F#事情的类型? - F# vs Scala - why do I need to tell F# the type of things? 值不是类型参数 F[] 的成员 - value is not a member of type parameter F[] Scala是否具有F#的“类型”? - Does Scala have an equivalent of F#'s “type of”? Scala通用类型函数限制,例如F# - Scala generic type function restriction like F# 如何在编译时要求类型参数是特征(而不是类或其他类型值)? - How to require at compile time that a type parameter be a trait (and not a class or other type value)? 在Scala中,如何针对具有类型参数的类型测试“Any”对象的类型? - In Scala, how to test the type of an 'Any' object against a type with type parameter?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM