在C#中实现模板方法模式 [英] Implementing the Template Method pattern in C#

查看:60
本文介绍了在C#中实现模板方法模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

模板方法模式提供了抽象基类具有不可覆盖的方法:该方法实现通用算法,并且不应在子类中覆盖.在Java中,模板方法在抽象基类中声明为 final ,在C#中, sealed 关键字具有相似的含义,但不能声明未覆盖的方法密封的.

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();
    }
}

我该如何解决这个问题?为什么不能阻止方法可以被子类覆盖(在C#中)?

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

推荐答案

sealed 修饰符仅对覆盖基类成员的函数成员有效,以阻止它们对派生类变为虚拟.在C#中,默认情况下,函数成员是非虚拟的(不同于Java).您仍然需要 class sealed 修饰符-默认情况下,类不是密封的.

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.

只需从方法中删除 sealed 修饰符,就可以了.

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

有关密封方法的更多详细信息,请参见C#4规范的10.6.5节(密封属性和事件分别在10.7.5节和10.8.4节中).

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).

当实例方法声明包含 sealed 修饰符时,该方法被称为密封方法.如果实例方法声明包含 sealed 修饰符,则它还必须包含 override 修饰符.使用 sealed 修饰符可以防止派生类进一步覆盖该方法.

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.

这篇关于在C#中实现模板方法模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆