假設存在類別 A : string (實際上 string 為 sealed 不可繼承,此為思想實驗)。
static void Show(object o) { Console.WriteLine("Object"); }
static void Show(string s) { Console.WriteLine("String"); }
static void Show(A a) { Console.WriteLine("A"); } // 假設 A 繼承 string
Show(null); // 呼叫 Show(A) - 最衍生類型
Show(""); // 呼叫 Show(string)
尋找最精確多載順序:
Show(int) - 不存在Show(ValueType) - int 繼承 ValueType,不存在Show(object) - ValueType 繼承 object,存在 → 選擇此多載此過程發生裝箱,IL 碼可見 box [mscorlib]System.Int32。
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
.maxstack 8
IL_0000: nop
IL_0001: ldnull
IL_0002: call void Program::Show(string)
IL_0007: nop
IL_0008: ldstr ""
IL_000d: call void Program::Show(string)
IL_0012: nop
IL_0013: ldc.i4.1
IL_0014: box [mscorlib]System.Int32 // 裝箱發生於此
IL_0019: call void Program::Show(object)
IL_001e: nop
IL_001f: ret
}
多載解析遵循「型別繼承鏈向上尋找最精確匹配」,值型別若無對應多載會經由裝箱轉為 object。