Implementing the Template Method pattern in C#

我是研究僧i 提交于 2021-02-04 15:31:34

问题


The template method pattern provides that the abstract base class has a not overridable method: this method implements the common algorithm and should not overridden in the subclasses. In Java the template method is declared final within the abstract base class, in C# the sealed keyword has a similar meaning, but a not overridden method can not be declared sealed.

public abstract class Base
{
    protected abstract AlgorithmStep1();

    protected abstract AlgorithmStep2();

    public sealed void TemplateMethod()   // sealed: compile error
    {
        AlgorithmStep1();
        AlgorithmStep2();
    }
}

How can I solve this problem? Why can not prevent a method can be overridden by subclasses (in C#)?


回答1:


The sealed modifier is only valid for function members which are overriding base class members, to stop them from being virtual for derived classes. Function members are non-virtual by default in C# (unlike Java). You still need the sealed modifier for a class though - classes aren't sealed by default.

Just remove the sealed modifier from your method and it should be fine.

See section 10.6.5 of the C# 4 spec for more details about sealed methods (sealed properties and events are in section 10.7.5 and 10.8.4 respectively).

When an instance method declaration includes a sealed modifier, that method is said to be a sealed method. If an instance method declaration includes the sealed modifier, it must also include the override modifier. Use of the sealed modifier prevents a derived class from further overriding the method.




回答2:


Just remove the sealed keyword. By default, methods are not overridable; subclasses cannot override them, only hide them.




回答3:


C# methods are sealed by default



来源:https://stackoverflow.com/questions/11974371/implementing-the-template-method-pattern-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!