简体   繁体   English

您如何从具有重载构造方法的抽象类派生

[英]How do you derive from an Abstract Class having overloaded Constructors

I have an Abstract Class having 2 overloaded constructors. 我有一个具有2个重载构造函数的Abstract类。 I want to require all derived classes to implement both constructors as both variations support some of the virtual methods provided by Class A that would be very beneficial of all the derived classes. 我想要求所有派生类都实现这两个构造函数,因为这两个变体都支持类A提供的某些虚拟方法,这对所有派生类都是非常有益的。 My model resembles the following: 我的模型类似于以下内容:

public abstract class A
{
    protected int _x {get;set;}
    protected int _y {get;set;}
    protected string _z {get;set;}

    public A(int x, int y)
    {
       _x = x;
       _y = y;
    }
    public A(int x, int y, string z)
    {
       _x = x;
       _y = y;
       _z = z;
    }
}

I know I can declare the 1st constructor like this: 我知道我可以这样声明第一个构造函数:

public class B : A { B(int x, int y) : base (x , y) {}

}

But how would one go about declaring the 2nd constructor of the Abstract class in the derived class? 但是,如何在派生类中声明Abstract类的第二个构造函数呢?

You don't inherit constructors at all. 您根本不会继承构造函数。 You declare whichever constructors you want, and make sure that each one chains appropriately, either to a base class constructor, or to another constructor in the same class. 您可以声明所需的任何构造函数,并确保每一个都正确链接到基类构造函数或同一类中的另一个构造函数。

So for example, you could have: 因此,例如,您可能有:

public class B : A
{
    public B(int x, int y) : base(x , y) {}    
    public B(int x, int y, string z) : base(x, y, z) {}

    public B() : base(0, 0, "Hello!") {}

    public B(int x) : this(x, 10, "Chained to B") {}
}

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

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