Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 我应该称之为基类';Windows服务中的方法?_C#_.net_Service_Windows Services - Fatal编程技术网

C# 我应该称之为基类';Windows服务中的方法?

C# 我应该称之为基类';Windows服务中的方法?,c#,.net,service,windows-services,C#,.net,Service,Windows Services,从ServiceBase派生时,我是否也应该调用基类的方法 protected override void OnStart(string[] args) { // // The stuff I do when the service starts. // base.OnStart(args); // Do I need to call this? } 我想我在编写服务时从未调用base.OnStart 但是,如果您这样做,请始终使基类调用方法的第一行,而不是最

ServiceBase
派生时,我是否也应该调用基类的方法

protected override void OnStart(string[] args)
{
    //
    // The stuff I do when the service starts.
    //

    base.OnStart(args); // Do I need to call this?
}

我想我在编写服务时从未调用base.OnStart


但是,如果您这样做,请始终使基类调用方法的第一行,而不是最后一行

简短的回答是肯定的,你应该这样做


在这个特定的例子中,OnStart方法的基本实现没有做任何重要的事情,但是这是一个可以随时更改的实现细节。一般来说,除非您有充分的理由不调用base方法,否则您应该始终调用base方法。

如果您使用ILSpy或类似工具对服务库进行反编译,您将看到OnStart、OnStop等不执行任何操作(至少在.NET 4.0/4.5中)

但是这种行为可能会在一段时间内发生变化,因此,如果您不调用它,在未来的.NET版本中可能会出现不想要的或不可预测的行为。

我认为调用那些base.OnEvent()方法是一个很好的实践。

我在读到的关于重写的所有内容都表明,总是首先调用base引用。我必须测试,但我认为编译器可能需要它。@KennyZ:编译器不需要它。你可以随时打电话,也可以不打。