![](/img/trans.png)
[英]C# Inheritance: How to invoke the base class constructor when i call the derived class constructor
[英]How to call base class constructor alone through derived class object in c#?
我在一次采访中得到了以下问题:“如何从派生类对象单独调用基类构造函数(默认构造函数)”。 该对象不应调用派生类的默认构造函数。 这怎么可能?
这是代码:
class a
{
public a()
{
MessageBox.Show("Base class called");
}
}
class b : a
{
public b()
{
MessageBox.Show("Derived class");
}
}
我只想显示基类构造函数,而没有调用派生类的构造函数。 我怎样才能做到这一点?
假设您有以下课程:
class Base
{
public Base() { }
}
class Derived : Base
{
public Derived() { }
}
创建派生类时会自动调用base
类的构造函数。 因此,根本不可能在不调用派生类的情况下调用基类构造函数。 唯一的方法是创建一个Base
类型的实例而不是Derived
,如果你创建一个Derived
它的构造函数肯定会被调用。
但是,如果您在Derived
有第二个构造函数直接调用Base
-one,您当然可以绕过派生类的默认构造函数:
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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.