문제

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#)?

도움이 되었습니까?

해결책

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.

다른 팁

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

C# methods are sealed by default

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top