如何在F#中正确继承C#泛型抽象类?
F#继承C#泛型抽象类的正确实现方式
背景
现有如下C#泛型抽象类:
public abstract class PaymentSystemBase< TPayInSettings, TPayOutSettings, TRefundSettings, TCashierContract, TPayoutContract > : IPaymentSystemInitializable, IPaymentSystem where TPayInSettings : BasePayInPaymentSystemSettings, new() where TPayOutSettings : BasePayOutPaymentSystemSettings, new() where TRefundSettings : BaseRefundPaymentSystemSettings, new() where TCashierContract : PaymentSystemBaseCashierContract, new() where TPayoutContract : PaymentSystemBasePayOutContract, new() { // 类实现代码 }
问题
尝试用F#继承该类时写了如下代码:
module Main = type CheckoutPaymentIdealUnitTest = inherit PaymentSystemBase< BasePayInPaymentSystemSettings, BasePayOutPaymentSystemSettings, BaseRefundPaymentSystemSettings, PaymentSystemBaseCashierContract, PaymentSystemBasePayOutContract > with member x = 1
IDE抛出错误:The type 'PaymentSystemBase<....>' is not an interface type
请问是否可以在F#中继承C#泛型抽象类?正确的实现方式是什么?期望得到类似C#中直接继承类的结构。
解答
可以在F#中继承C#泛型抽象类,错误原因是F#中继承类的语法和继承接口不同:
- 继承接口时使用
inherit 接口类型 with - 继承类时,需要先通过
= 继承类()(如果有构造函数参数则传入)的形式声明继承,再用with扩展成员。
正确的实现代码如下:
module Main = type CheckoutPaymentIdealUnitTest() = inherit PaymentSystemBase< BasePayInPaymentSystemSettings, BasePayOutPaymentSystemSettings, BaseRefundPaymentSystemSettings, PaymentSystemBaseCashierContract, PaymentSystemBasePayOutContract >() member _.TestProperty = 1
关键语法说明
- 首先声明F#类的构造函数:
type CheckoutPaymentIdealUnitTest() =,如果基类需要构造参数,这里要对应传入。 - 用
inherit 基类类型()继承C#泛型抽象类,末尾的()是调用基类的无参构造函数(因为C#泛型抽象类的类型参数都有new()约束,基类应该有可访问的无参构造)。 - 用
with关键字添加自定义成员,比如示例中的TestProperty。
这样就能实现和你期望的C#类结构等价的F#类。
内容的提问来源于stack exchange,提问作者Arthur Lomakin
相关产品推荐
相关产品推荐

