You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

关键语法说明

  1. 首先声明F#类的构造函数:type CheckoutPaymentIdealUnitTest() =,如果基类需要构造参数,这里要对应传入。
  2. 用 inherit 基类类型() 继承C#泛型抽象类,末尾的 () 是调用基类的无参构造函数(因为C#泛型抽象类的类型参数都有new()约束,基类应该有可访问的无参构造)。
  3. 用 with 关键字添加自定义成员,比如示例中的TestProperty。

这样就能实现和你期望的C#类结构等价的F#类。

内容的提问来源于stack exchange,提问作者Arthur Lomakin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 08:43:11