简体   繁体   English

从ServiceBase派生时,我是否调用基础构造函数?

[英]Do I call the base constructor when deriving from ServiceBase?

Microsoft .NET documentation for the System.ServiceProcess.ServiceBase class constructor says: System.ServiceProcess.ServiceBase类构造函数的Microsoft .NET文档说:

If you override the base class constructor, you should explicitly call it in the constructor of your derived class. 如果重写基类构造函数,则应在派生类的构造函数中显式调用它。

In Using Constructors in the Microsoft C# Programming Guide, it says: 在“Microsoft C#编程指南”中的“ 使用构造函数 ”中,它说:

In a derived class, if a base-class constructor is not called explicitly by using the base keyword, the default constructor, if there is one, is called implicitly. 在派生类中,如果未使用base关键字显式调用基类构造函数,则会隐式调用默认构造函数(如果有)。

So do I need to call the base constructor explicitly or not, and why? 所以我需要明确地调用基本构造函数,为什么?

It doesn't matter. 没关系。 These compile to the same IL: 这些编译成相同的IL:

public class Service1 : ServiceBase
{
    public Service1() : base() { }
}
public class Service1 : ServiceBase
{
    public Service1() { }
}

I don't know why ServiceBase recommends explicitly calling it. 我不知道为什么ServiceBase建议显式调用它。 I'd go with the other suggestion, since it seems to make more sense. 我会选择其他建议,因为它似乎更有意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从框架控件继承时,应该调用基本构造函数吗? - When inheriting from a framework control, should I call the base constructor? 我怎么称呼这个和基本构造函数 - How do I call both this and base constructor 如何调用构造函数初始化器 base() 和 this()? - how do i call both constructor initializers, base() and this()? 当我可以在继承自其的类中执行相同的操作时,为什么要在类中设置构造函数以设置基本参数? - Why set up a constructor in a class to set a base parameter when I could do the same in a class it inherits from? 如何在没有自己的构造函数的基类型函数内调用泛型类型的构造函数? - How do I call a constructor on a generic type within a function of a base type without its own constructor? C#继承:当我调用派生类构造函数时,如何调用基类构造函数 - C# Inheritance: How to invoke the base class constructor when i call the derived class constructor 如何从调用基本构造函数的类继承? - How do I inherit from class that calls base constructor? 我应该如何使用从通用基础 class 派生的 class 调用基础 class 构造函数? - How should I call a base class constructor with a class derived from a generic base class? 为什么我可以调用基本构造函数 - Why I can call base constructor 为什么我不能调用基类的构造方法? - Why I cannot call the base class Constructor?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM