base 關鍵字核心用法
- 呼叫基底類別建構函式:
base(參數) 在衍生類別建構函式中指定呼叫哪個基底建構函式
- 存取基底類別成員:
base.成員 存取被衍生類別隱藏的基底成員(方法、屬性、欄位)
- 限制:只能在建構函式、實例方法、屬性存取子中使用;靜態方法中禁止
建構函式鏈實戰範例
using System;
namespace Traffic
{
// 基底類別:Vehicle
public class Vehicle
{
private string _name;
private int _speed;
public Vehicle() { Console.WriteLine("Vehicle 無參數建構函式"); }
public Vehicle(string name)
{
_name = name;
Console.WriteLine($"Vehicle(string) - {name}");
}
public Vehicle(string name, int speed)
{
_name = name;
_speed = speed;
Console.WriteLine($"Vehicle(string, int) - {name}, {speed}km/h");
}
public void GetName() => Console.WriteLine($"名稱:{_name}");
}
// 衍生類別:Car
public class Car : Vehicle
{
public Car() : base() // 明確呼叫基底無參數建構函式
{
Console.WriteLine("Car 無參數建構函式");
base.GetName(); // 呼叫基底方法
}
// 關鍵:base(name, speed) 傳遞參數給基底建構函式
// 執行順序:Vehicle(string, int) → Car(string, int)
public Car(string name, int speed) : base(name, speed)
{
Console.WriteLine("Car(string, int) 建構函式");
}
}
// 第二層衍生:GaoJiCar
public class GaoJiCar : Car
{
// 執行順序:Vehicle(string, int) → Car(string, int) → GaoJiCar()
public GaoJiCar() : base("長安", 124)
{
Console.WriteLine("GaoJiCar 無參數建構函式");
}
}
class Program
{
static void Main()
{
Console.WriteLine("=== 建立 Car() ===");
Car c1 = new Car();
Console.WriteLine("\n=== 建立 Car(\"吉利\", 300) ===");
Car c2 = new Car("吉利", 300);
Console.WriteLine("\n=== 建立 GaoJiCar() ===");
GaoJiCar c3 = new GaoJiCar();
}
}
}
執行輸出與順序分析
=== 建立 Car() ===
Vehicle 無參數建構函式
Car 無參數建構函式
名稱:
=== 建立 Car("吉利", 300) ===
Vehicle(string, int) - 吉利, 300km/h
Car(string, int) 建構函式
=== 建立 GaoJiCar() ===
Vehicle(string, int) - 長安, 124km/h
Car(string, int) 建構函式
GaoJiCar 無參數建構函式
關鍵觀察
- 基底建構函式先執行:無論衍生類別建構函式內容為何,
base(...) 指定的基底建構函式永遠最先完成
- 參數直接透傳:
base(name, speed) 中的 name、speed 直接對應衍生類別建構函式參數,不需重新宣告型別
- 多層繼承鏈:
GaoJiCar → Car → Vehicle,每層若指定 base(...) 皆會依序執行對應基底建構函式
- 未指定 base 時:預設呼叫基底類別無參數建構函式(若不存在則編譯錯誤)
base 存取被隱藏成員
public class Base
{
public void Show() => Console.WriteLine("Base.Show()");
}
public class Derived : Base
{
public new void Show() => Console.WriteLine("Derived.Show()"); // 隱藏基底
public void CallBaseShow() => base.Show(); // 明確呼叫基底版本
}
this vs base 快速對照
| 場景 | this | base |
| 呼叫建構函式 | this(...) 呼叫同類別其他建構函式 | base(...) 呼叫基底類別建構函式 |
| 存取成員 | this.成員 當前實例成員(區分同名參數) | base.成員 基底類別成員(穿透隱藏) |
| 索引子宣告 | this[int i] 定義索引子 | 不適用 |
| 擴充方法 | this Type param 第一個參數修飾詞 | 不適用 |
| 靜態方法 | 禁止使用 | 禁止使用 |