简体   繁体   English

如何以及何时在C#中调用基类构造函数

[英]How and when to call the base class constructor in C#

如何以及何时在C#中调用基类构造函数

You can call the base class constructor like this: 您可以像这样调用基类构造函数:

// Subclass constructor
public Subclass() 
    : base()
{
    // do Subclass constructor stuff here...
}

You would call the base class if there is something that all child classes need to have setup. 如果存在所有子类需要设置的内容,则可以调用基类。 objects that need to be initialized, etc... 需要初始化的对象等...

Hope this helps. 希望这可以帮助。

It's usually a good practice to call the base class constructor from your subclass constructor to ensure that the base class initializes itself before your subclass. 从子类构造函数中调用基类构造函数通常是一种很好的做法,以确保基类在子类之前初始化自身。 You use the base keyword to call the base class constructor. 您使用base关键字来调用基类构造函数。 Note that you can also call another constructor in your class using the this keyword. 请注意,您还可以使用this关键字在类中调用另一个构造函数。

Here's an example on how to do it: 以下是如何执行此操作的示例:

public class BaseClass
{
    private string something;

    public BaseClass() : this("default value") // Call the BaseClass(string) ctor
    {
    }

    public BaseClass(string something)
    {
        this.something = something;
    }

    // other ctors if needed
}

public class SubClass : BaseClass
{
    public SubClass(string something) : base(something) // Call the base ctor with the arg
    {
    }

    // other ctors if needed
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM