【问题标题】:How and when to call the base class constructor in C#如何以及何时在 C# 中调用基类构造函数
【发布时间】:2011-03-17 06:05:40
【问题描述】:

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

【问题讨论】:

标签: c#


【解决方案1】:

你可以像这样调用基类构造函数:

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

如果所有子类都需要设置某些东西,您将调用基类。需要初始化的对象等...

希望这会有所帮助。

【讨论】:

  • 您也可以像这样调用基类构造函数:public Subclass() {} -- 这与您的示例具有完全相同的行为。
【解决方案2】:

从子类构造函数中调用基类构造函数通常是一个好习惯,以确保基类在子类之前初始化自身。您使用base 关键字来调用基类构造函数。请注意,您还可以使用 this 关键字在您的类中调用另一个构造函数。

下面是一个例子:

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
}

【讨论】:

  • 这不仅仅是一个好习惯,它还是编译器强制执行的要求。 A base constructor will get called whether you like it or not.
  • 好点...如果您没有明确调用特定的ctor,它将调用默认的ctor。
  • 在 Flash/AS3 中,您可以在子类构造函数中工作,然后在中途调用“super()”以运行基类构造函数,然后在子类构造函数中继续执行更多代码。在 C# 中,您必须先调用基类构造函数,然后才能运行子类构造函数中的任何代码。
  • 不过有一种解决方法。如果你在基类中创建一个虚方法,并在你的子类中覆盖它,那么你可以将你需要运行的代码放在被覆盖的方法中,并从基类中调用它。
猜你喜欢
  • 2010-11-19
  • 1970-01-01
  • 2014-07-26
  • 2012-09-28
  • 2021-03-14
  • 2013-03-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多