在C#中,构造函数不能直接继承,但可以通过以下方式实现继承关系:
base
关键字调用基类的构造函数。这样,当创建派生类对象时,基类的构造函数将被自动调用。例如:public class BaseClass
{
public BaseClass()
{
Console.WriteLine("BaseClass constructor called.");
}
}
public class DerivedClass : BaseClass
{
public DerivedClass() : base()
{
Console.WriteLine("DerivedClass constructor called.");
}
}
public class Program
{
public static void Main()
{
DerivedClass obj = new DerivedClass();
}
}
输出结果:
BaseClass constructor called.
DerivedClass constructor called.
public class BaseClass
{
public string Property { get; set; }
public BaseClass(string property)
{
Property = property;
Console.WriteLine("BaseClass constructor called.");
}
}
public class DerivedClass : BaseClass
{
public DerivedClass(string property) : base(property)
{
Console.WriteLine("DerivedClass constructor called.");
}
}
public class Program
{
public static void Main()
{
DerivedClass obj = new DerivedClass("Hello, World!");
}
}
输出结果:
BaseClass constructor called.
DerivedClass constructor called.
在这两种方法中,基类的构造函数或初始化器将在派生类构造函数之前被调用,从而实现继承关系。