在 C# 中从子类的构造函数调用基类的构造函数
Muhammad Maisam Abbas
2024年2月16日
Csharp
Csharp Class

本教程将讨论从 C# 中的子类的构造函数调用基类的构造函数的方法。
在 C# 中从子类的构造函数调用基类的默认构造函数
在 C# 中,当我们创建子类的实例时,编译器会自动调用基类的默认构造函数。下面的代码示例中显示了这种现象。
using System;
namespace call_constructor_of_base_class {
public class baseClass {
public baseClass() {
Console.WriteLine("This is the Base Class");
}
}
public class childclass : baseClass {
public childclass() {
Console.WriteLine("This is the Child Class");
}
}
class Program {
static void Main(string[] args) {
childclass c = new childclass();
}
}
}
输出:
This is the Base Class
This is the Child Class
在上面的代码中,baseClass
是基类,而 childclass
是继承 baseClass
的子类。当我们创建子类 childclass
的实例时,编译器会自动调用 baseClass
的默认构造函数。baseClass
的构造函数在 childclass
的构造函数之前执行。此方法不能用于将参数从子类的构造函数传递给基类的构造函数。
在 C# 中使用 base
关键字将参数从子类的构造函数传递给基类的构造函数
如果要从子类的构造函数将参数传递给基类的构造函数,则必须使用 base
关键字。base
关键字指定在创建子类的实例时应调用基类的构造方法。以下代码示例向我们展示了如何使用 C# 中的 base
关键字将子类的构造函数中的参数传递给基类的构造函数。
using System;
namespace call_constructor_of_base_class {
public class baseClass {
public baseClass() {
Console.WriteLine("This is the Base Class");
}
public baseClass(int x) {
Console.WriteLine("The Child class passed {0} to the Base Class", x);
}
}
public class childclass : baseClass {
public childclass(int a) : base(a) {
Console.WriteLine("This is the Child Class");
}
}
class Program {
static void Main(string[] args) {
childclass c = new childclass(10);
}
}
}
输出:
The Child class passed 10 to the Base Class
This is the Child Class
在上面的代码中,我们将 10 传递给子类 childclass
的构造函数的基类 baseClass
的参数化构造函数。
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.
LinkedIn