首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 方法多載決策邏輯:從 int 到 Object 的裝箱與最佳匹配原則 (第 4 部分)

     編輯:關於C語言

假設情境

假設存在類別 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(1) 呼叫 Show(object)?

尋找最精確多載順序:

  1. Show(int) - 不存在
  2. Show(ValueType) - int 繼承 ValueType,不存在
  3. Show(object) - ValueType 繼承 object,存在 → 選擇此多載

此過程發生裝箱,IL 碼可見 box [mscorlib]System.Int32。

IL 碼驗證

.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。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved