如何最好地防止继承者在基础中调用密封的重写虚方法。 [英] How best to prevent an inheritor from calling a sealed overridden virtual method in a base.

查看:49
本文介绍了如何最好地防止继承者在基础中调用密封的重写虚方法。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究一些Windows服务框架代码,我采用的模式是创建一个继承自 ServiceBase <的框架服务类
ApplicationService / strong>,在那里我覆盖
OnStart 等。

I'm working on some Windows Service framework code, a pattern I'm adopting is to create a framework service class ApplicationService that inherits from ServiceBase, in there I override OnStart etc.

我不希望从 ApplicationService 派生的开发人员覆盖
OnStart (因为存在风险,他们不会调用我的基本方法,或者如果他们这样做,他们可能会在其覆盖中的错误点调用它。)

I do not want developers who derive from ApplicationService to override OnStart (because there's a risk they'll not call my base method or if they do they may call it at the wrong point within their override).

因此模式适用于 ApplicationService 覆盖
OnStart
(在 ServiceBase 中),但请将其标记为已密封并在我的重写方法执行我需要做的事情(内务处理),然后调用一个新的虚拟方法
OnStartService ()。这些当然可以被开发人员覆盖,这是预期的。

So the pattern is for ApplicationService to override OnStart (in ServiceBase) but mark it as sealed and in my overridden method do what I need to do (housekeeping stuff) and then call a new virtual method OnStartService(). These of course can be overridden by developers, this is expected.

这意味着我的基础 OnStart 被系统调用,然后我调用被覆盖的$ b由开发人员实施的$ b OnStartService ,效果很好。

This means that my base OnStart gets called by the system and then I call the overridden OnStartService implemented by the developer, this works fine.

但是,虽然他们无法覆盖 OnStart (在我的基础或
ServiceBase
)他们可以选择调用它而不打算调用它(系统除外)。

However although they cannot override OnStart (in my base or ServiceBase) they can if they so choose call it and its not intended to be called (other than by the system).

这个问题是否能够得到最好的解决?使用界面?

Is this problem best solved by using an interface?

K




推荐答案

您是否已经尝试密封

public class ApplicationService : ServiceBase
{
   protected sealed override void OnStart( string[] args )
   {
      . . .
   }
}


这篇关于如何最好地防止继承者在基础中调用密封的重写虚方法。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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