在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.
在這兩種方法中,基類的構造函數或初始化器將在派生類構造函數之前被調用,從而實現繼承關系。