且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

类继承,强制新类实现某些功能

更新时间:2022-06-01 02:05:47

这是什么时候您希望将基类和基本方法标记为 abstract

This is when you want to mark the base class and the base method as abstract.

abstract class Animal 
{
    public abstract void Walk(); 
}

派生类必须实现 Walk 以便实例化。

Derived classes will have to implement Walk in order to be instantiated.

class Cat : Animal 
{
    public override void Walk() { }
}

注意:此更改使 Animal 本身不可实例化,对它的所有引用都将通过更多的派生类。

Note: this change makes Animal not instantiable on its own, all references to it would be via more derived classes.

Animal animal = new Cat();




这是我的问题,有没有办法强迫猫改写
基础的Walk()方法? 因此,如果另一位开发人员添加了Dog类,那么
将***实现自己的Walk方法(即使它是
只是base.Walk())

这是你有一个断开或相反目标的地方。要强制子项实现方法,请将其标记为抽象。为了让孩子选择使用基本实现,它需要是虚拟的,这将使其成为可选的覆盖。即使您基本上使用模板方法模式并使算法摘要的 parts 将实现推送到较低的类,问题仍然是相同的:您也不能强制覆盖,同时保留默认实现。*

This is where you have a disconnect, or opposing goals. To force children to implement a method, you mark it abstract. To allow the child to elect to use the base implementation, it would need to be virtual, which would then make it optional to override. Even if you were to basically use a template method pattern and make parts of the algorithm abstract to push the implementation into lower classes, the problem remains the same: you cannot force an override while also leaving a default implementation.*

您需要确定是否要部分或全部实施基本实施。

You need to determine if you want to have a base implementation, in part or in whole.

*理论上你理论上有 abstract void Walk(); protected void WalkImpl(){} 在基础中,允许孩子选择调用 WalkImpl 如果他们不想提供他们的自己的实施。

*You chould theoretically have abstract void Walk(); protected void WalkImpl() { } in the base, which would allow the children to choose to invoke WalkImpl if they didn't want to provide their own implementation.

class Cat : Animal
{
     protected override void Walk() { base.WalkImpl(); }
}

然而,我不确定我对此的看法。您基本上通过强制覆盖同时仍然允许它们使用默认行为来使派生类的作者生活更加困难。 如果可以使用默认行为,只需使用 virtual 并信任派生类的作者,以便在他们认为合适时覆​​盖它们。

I'm not sure how I feel about this, however. You're basically making the derived classes' authors' lives more difficult by forcing an override while still allowing them to use a default behavior. If the default behavior can be used, simply go with virtual and trust authors of derived classes to override when they feel it is appropriate.