在 C# 中,:this()
和 :base()
都用于构造函数的重载和继承,但它们有不同的用途和上下文:
1. :this()
-
用途:用于调用当前类中的其他构造函数(构造函数重载)。
-
场景:当你希望一个构造函数先执行另一个构造函数中的逻辑时使用。
-
示例 :
csharppublic class MyClass { public MyClass() : this("default") // 调用下面的构造函数 { Console.WriteLine("无参构造函数"); } public MyClass(string name) { Console.WriteLine($"带参构造函数,name: {name}"); } }
输出 (当调用
new MyClass()
时):带参构造函数,name: default 无参构造函数
2. :base()
-
用途:用于调用基类(父类)的构造函数。
-
场景:在继承关系中,子类构造函数需要初始化基类的成员时使用。
-
示例 :
csharppublic class BaseClass { public BaseClass() { Console.WriteLine("基类构造函数"); } } public class DerivedClass : BaseClass { public DerivedClass() : base() // 显式调用基类构造函数(可省略) { Console.WriteLine("子类构造函数"); } }
输出 (当调用
new DerivedClass()
时):基类构造函数 子类构造函数
关键区别
特性 | :this() |
:base() |
---|---|---|
调用目标 | 当前类的其他构造函数 | 基类的构造函数 |
使用场景 | 构造函数重载(简化代码) | 继承(初始化基类成员) |
是否可选 | 可选(根据需要) | 可选(如果基类有无参构造函数,可省略) |
其他注意事项
- 如果省略
:base()
,编译器会自动调用基类的无参构造函数(如果基类没有无参构造函数,则必须显式调用)。 :this()
和:base()
必须出现在构造函数声明之后,且只能选择其中之一(不能同时使用)。- 它们可以带参数,例如
:this("hello")
或:base(42)
。
示例(结合使用)
csharp
public class Animal
{
public Animal(string name)
{
Console.WriteLine($"Animal: {name}");
}
}
public class Dog : Animal
{
public Dog() : this("Buddy") // 调用当前类的其他构造函数
{
Console.WriteLine("Dog()");
}
public Dog(string name) : base(name) // 调用基类构造函数
{
Console.WriteLine($"Dog(name: {name})");
}
}
输出 (当调用 new Dog()
时):
Animal: Buddy
Dog(name: Buddy)
Dog()