我在一次面试中得到了以下问题:"如何从派生类对象单独调用基类构造函数(默认构造函数)"。该对象不应调用派生类默认构造函数。怎么可能?
这是代码:
class a
{
public a()
{
MessageBox.Show("Base class called");
}
}
class b : a
{
public b()
{
MessageBox.Show("Derived class");
}
}
我只想显示基类构造函数,而不调用派生类中的构造函数。我怎样才能做到这一点?
这个问题的措辞方式听起来像一个谜语,但我认为它的意思是"如何从派生类的非默认构造函数调用基类默认构造函数"。
无论如何,这都会隐式发生,但是如果你想明确一点,你正在寻找 base
关键字来指定要在基类中调用哪个构造函数:
public Derived(object param) : base()
{
}
不调用派生类的默认构造函数的唯一方法是在派生类中使用非默认构造函数并使用该构造函数实例化对象。
有关包含默认和非默认构造函数的演示,请参阅此小提琴。
假设您有以下类:
class Base
{
public Base() { }
}
class Derived : Base
{
public Derived() { }
}
创建派生构造函数时会自动调用 base
-class'-构造函数。因此,如果不调用派生类构造函数,就根本不可能调用基类构造函数。唯一的方法是创建一个类型为 Base
而不是 Derived
的实例,如果您创建一个Derived
它的构造函数肯定会被调用。
但是,如果你在Derived
中有第二个构造器直接调用Base
-one,你当然可以绕过派生类的defaulöt构造函数:
class Derived : Base
{
public Derived() { }
public Derived(params object[] args) : base() { }
}
现在,您可以进行以下调用:
Derived d = new Derived(); // will call both default-constructors
Derived d1 = new Derived(null); // calls the params-overloaded constructor and not its default one
试试这段代码:
class Base
{
public Base() {
Console.WriteLine("BaseClass Const.");
}
}
class Derived : Base
{
public Derived() { }
public Derived(params object[] args) : base() { }
}
public class Program
{
public static void Main(string[] args)
{
Derived d = new Derived(null) ;
}
}
预期输出 :
BaseClass Const.