如何强制在 C# 中调用基本构造函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/324066/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 23:13:47  来源:igfitidea点击:

How can I force the base constructor to be called in C#?

c#asp.netoopconstructorc#-2.0

提问by Tom Robinson

I have a BasePage class which all other pages derive from:

我有一个 BasePage 类,所有其他页面都源自:

public class BasePage

This BasePage has a constructor which contains code which must always run:

这个 BasePage 有一个构造函数,其中包含必须始终运行的代码:

public BasePage()
{
    // Important code here
}

I want to force derived classes to call the base constructor, like so:

我想强制派生类调用基本构造函数,如下所示:

public MyPage
    : base()
{
    // Page specific code here
}

How can I enforce this (preferably at compile time)?

如何强制执行此操作(最好在编译时)?

采纳答案by Jon Skeet

The base constructor will always be called at some point. If you call this(...)instead of base(...)then that calls into another constructor in the same class - which again will have to either call yet another sibling constructor or a parent constructor. Sooner or later you will always get to a constructor which either calls base(...)explicitly or implicitly calls a parameterless constructor of the base class.

基构造函数将始终在某个时刻被调用。如果你调用this(...)而不是base(...)then 调用同一个类中的另一个构造函数 - 这又将不得不调用另一个同级构造函数或父构造函数。迟早你总会得到一个构造函数,它要么base(...)显式调用,要么隐式调用基类的无参数构造函数。

See this articlefor more about constructor chaining, including the execution points of the various bits (such as variable initializers).

有关构造函数链的更多信息,包括各个位(例如变量初始化程序)的执行点,请参阅此文章

回答by Johannes Schaub - litb

The base class constructor taking no arguments is automatically run if you don't call any other base class constructor taking arguments explicitly.

如果您不显式调用任何其他带参数的基类构造函数,则不带参数的基类构造函数将自动运行。

回答by Wilka

The base class constructor is always called, even if you don't call it explicitly. So you don't need to do any extra work to make sure that happens.

基类构造函数总是被调用,即使你没有显式调用它。所以你不需要做任何额外的工作来确保发生这种情况。

回答by Pop Catalin

One of the base constructors always needs to be called, and the default one is called when the base constructor is not explicitly stated.

始终需要调用基构造函数之一,当未明确声明基构造函数时,将调用默认构造函数。

Edit: rephrased for clarity.

编辑:为清楚起见重新表述。