简体   繁体   English

抽象类型定义f#

[英]Abstract type definitions f#

I am looking to define a couple of types in an interface or abstract class with the implementation left unspecified. 我正在尝试在接口或抽象类中定义几种类型,而实现的方式尚未指定。 I then want to inherit from this interface in another, so that i can specify my methods in interface2 with the types that were defined in the first interface. 然后,我想从另一个接口继承,以便我可以在interface2中使用在第一个接口中定义的类型指定我的方法。

Eg: 例如:

type Interface1 =
      type MyType1
      type MyType2

type Interface2 =
      inherit Interface1
      abstract member method1 : MyType1*MyType2 -> int


Module MyModule =

The idea is that i want the module to then implement interface2, so it should implement MyType1 and MyType2, and method1. 这个想法是我希望模块然后实现interface2,因此它应该实现MyType1和MyType2,以及method1。

The reason i'm not doing all this in a signature file is because i want to be able to implement type1 and 2 in c# as well, but implementing Interface1. 我没有在签名文件中完成所有这些操作的原因是因为我也希望能够在c#中实现type1和2,但要实现Interface1。

Can anyone help me with this? 谁能帮我这个?

I think what you really want is to use generics: 我认为您真正想要的是使用泛型:

type Interface2<'T1,'T2> =
      abstract member method1 : 'T1*'T2 -> int

You don't need Interface1 at all here. 您在这里根本不需要Interface1 Then if have Type1 and Type2 implemented in C# (or in F# for that matter), you C# class can inherit from Interface2<Type1,Type2> and you're all set. 然后,如果在C#中实现Type1Type2 (或者在F#中实现),则C#类可以从Interface2<Type1,Type2>继承Interface2<Type1,Type2>

Edit: If I've understood your comment correctly, you want to set some constraints on 'T1 and 'T2 such that they implement specific interfaces. 编辑:如果我正确理解了您的评论,则要对'T1'T2设置一些约束,以使它们实现特定的接口。 The generic names of all this ( 'T1 , Type1 , and so on) is starting to confuse me, so I'm going to use specific names for an example. 所有这些的通用名称( 'T1Type1等)开始让我感到困惑,因此我将使用特定名称作为示例。 Let's say that you have a generic IKeyboard interface and a generic IMouse interface, and you want your library's users to implement a specific keyboard and mouse class for your method. 假设您有一个通用的IKeyboard接口和一个通用的IMouse接口,并且希望库的用户为您的方法实现特定的键盘和鼠标类。 In other words, the 'T1 type above must derive from IKeyboard , and the 'T2 type above must derive from IMouse . 换句话说,上面的'T1类型必须从IKeyboard派生,而上面的'T2类型必须从IMouse派生。 In that case, type constraints are what you're looking for: 在这种情况下,您要寻找的是类型约束

type IKeyboard = class end
type IMouse = class end

type IInputDevices =
    abstract member getInput<'K,'M when 'K :> IKeyboard and 'M :> IMouse> : 'K*'M -> int

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM