同一類別中,方法名稱相同,參數列表不同(個數、型別、順序),與回傳型別無關。
static void Show(string s) => Console.WriteLine("String");
static void Show(object o) => Console.WriteLine("Object");
static void Main()
{
Show(null); // String(null 推斷為 string,最精確)
Show(""); // String
object o = "hi"; Show(o); // Object(靜態型別為 object)
Show(1); // Object(int→object 裝箱,無 int 多載)
}
IL 驗證:Show(null) 產生 call void Show(string);Show(1) 含 box int32 指令。
static void Show(string s) => Console.WriteLine("String");
static void Show(Program p) => Console.WriteLine("Program"); // Program 與 string 無繼承關係
static void Main() { Show(null); } // CS0121:無法決定 string 或 Program 較精確
static void Show(object o) => Console.WriteLine("Object");
static void Show(ValueType v) => Console.WriteLine("ValueType"); // 若存在
// Show(1) 會優先匹配 ValueType(int 繼承 ValueType),再 fallback Object
object 多載時,考慮同時提供常用值型別(int、double、bool)多載以避免裝箱。params 陣列多載時,置於最後;編譯器優先匹配固定參數版本。LoadFile/LoadStream)。