同一類別中定義同名但參數簽章不同的多個方法。編譯器在編譯期根據呼叫端提供的實際引數型別、數量、順序進行靜態綁定,選擇最佳匹配。
public class Vehicle {
public int Wheels { get; set; }
public float Weight { get; set; }
// 無參數建構子:使用預設值
public Vehicle() : this(4, 1500f) { }
// 兩參數建構子:完整初始化
public Vehicle(int wheels, float weight) {
Wheels = wheels;
Weight = weight;
}
public void Show() => Console.WriteLine($"Wheels: {Wheels}, Weight: {Weight}kg");
}
// 使用
var v1 = new Vehicle(); // 呼叫無參數版
var v2 = new Vehicle(2, 200f); // 呼叫兩參數版
public class Student {
public string Name { get; }
public int Age { get; }
public float Weight { get; }
public Student(string name, int age, float weight) { Name = name; Age = age; Weight = weight; }
// 多載:比較整數 (年齡)
public int Max(int x, int y) => x > y ? x : y;
// 多載:比較浮點數 (體重)
public float Max(float x, float y) => x > y ? x : y;
}
// 呼叫端無需記住不同方法名
var s1 = new Student("Mike", 21, 70f);
var s2 = new Student("John", 20, 65f);
Console.WriteLine($"Max Age: {s1.Max(s1.Age, s2.Age)}");
Console.WriteLine($"Max Weight: {s1.Max(s1.Weight, s2.Weight)}");
// 核心多載
WriteLine();
WriteLine(bool value);
WriteLine(char value);
WriteLine(int value);
WriteLine(uint value);
WriteLine(long value);
WriteLine(ulong value);
WriteLine(float value);
WriteLine(double value);
WriteLine(decimal value);
WriteLine(string value);
WriteLine(object value);
WriteLine(char[] buffer);
WriteLine(string format, object arg0);
WriteLine(string format, object arg0, object arg1);
WriteLine(string format, object arg0, object arg1, object arg2);
WriteLine(string format, params object[] args);
// 共 19 個公開多載 (實際更多)
int 優於 long),且無任何引數轉換「更差」。
void M(int x) { }
void M(long x) { }
M(5); // OK,選 int 版本 (5 為 int 常值)
void N(object o) { }
void N(string s) { }
N(null); // CS0121:null 同時適用 object 與 string
// 解決:N((string)null) 或 N((object)null)
| 機制 | 範圍 | 關鍵字 | 綁定時機 | 目的 |
|---|---|---|---|---|
| 多載 | 同一類別 | 無 | 編譯期 | 提供多種參數介面 |
| 覆寫 | 衍生類別 | override | 執行期 | 多態行為變化 |
| 隱藏 | 衍生類別 | new | 編譯期 | 替換基類別成員 (非多態) |
params、optional parameters、Builder pattern。