You need to enable JavaScript to run this app. C# 强制派生类实现指定签名方法的解决方案(abstract/virtual场景)
优惠活动
大模型
产品
解决方案
定价
更多

C# 强制派生类实现指定签名方法的解决方案(abstract/virtual场景)

需求说明

现有一个abstract class BaseClass,希望强制所有class Derived: BaseClass派生类都重写foo方法,且满足以下规则:

  • 继承 BaseClass 的非抽象类必须自行实现foo(效果同abstract关键字的约束)
  • BaseClass 必须提供foo的基础实现,派生类可直接调用(效果同virtual关键字的特性)
  • [原需求中要求派生类foo签名为static(类本身非静态)的条目已编辑移除]
  • foo的参数类型为对应派生类类型/this.GetType()类型,优先不改动 BaseClass 的方法签名

目前要同时满足除第3点外的多个要求难度较高甚至看似无法实现,以下是表达需求的伪代码:

public abstract class BaseClass
{
    bool baseBool;
    public abstract virtual static bool foo(BaseClass b1, BaseClass b2)
    {
        //sample code
        return b1.baseBool ^ b2.baseBool;
    }
}

public class Derived: BaseClass
{
    bool derivedBool;
    public static override bool foo(Derived d1, Derived d2)
    {
        //sample code
        return base.foo(d1, d2) && d1.derivedBool ^ d2.derivedBool;
    }
}

基于CRTP模式的实现方案

public abstract class BaseClass
{
    bool baseBool;
    public abstract bool foo(BaseClass b1, BaseClass b2);
}

public abstract class BaseClassWrappedCRTP<T>: BaseClass where T: BaseClassWrappedCRTP<T>
{
    public override bool foo(BaseClass b1, BaseClass b2)
    {
        //sample code
        return (b1.baseBool ^ b2.baseBool) && fooWrappedCRTP((T)b1, (T)b2);
    }

    protected abstract bool fooWrappedCRTP(T d1, T d2);
}

public class Derived: BaseClassWrappedCRTP<Derived>
{
    bool derivedBool;
    protected override bool fooWrappedCRTP(Derived d1, Derived d2)
    {
        //sample code
        return d1.derivedBool ^ d2.derivedBool;
    }
}

注意事项

如果 Derived 为abstract class Derived: BaseClassWrappedCRTP<Derived>,则需要定义abstract class DerivedWrappedCRTP<T>: Derived where T: DerivedWrappedCRTP<T>才能按该方式继续继承foo方法(前提是确实需要访问非泛型的Derived类)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 20:03:03