C# 中的方法過載是什麼?


在 C# 中,具有相同名稱但引數不同的兩個或多個方法就是方法過載。

C# 中的方法過載可以透過更改引數的數量和引數的資料型別來執行。

假設您有一個列印數字乘積的函式,那麼我們的過載方法將具有相同名稱但不同的引數數量 -

public static int mulDisplay(int one, int two) { }
public static int mulDisplay(int one, int two, int three) { }
public static int mulDisplay(int one, int two, int three, int four) { }

下面是一個顯示如何實現方法過載的示例 -

示例

 線上演示

using System;
public class Demo {
   public static int mulDisplay(int one, int two) {
      return one * two;
   }

   public static int mulDisplay(int one, int two, int three) {
      return one * two * three;
   }

   public static int mulDisplay(int one, int two, int three, int four) {
      return one * two * three * four;
   }
}

public class Program {
   public static void Main() {
      Console.WriteLine("Multiplication of two numbers: "+Demo.mulDisplay(10, 15));
      Console.WriteLine("Multiplication of three numbers: "+Demo.mulDisplay(8, 13, 20));
      Console.WriteLine("Multiplication of four numbers: "+Demo.mulDisplay(3, 7, 10, 7));
   }
}

輸出

Multiplication of two numbers: 150
Multiplication of three numbers: 2080
Multiplication of four numbers: 1470

更新於:20-6-2020

2K+ 次瀏覽

開啟您的 事業

完成課程後獲得認證

開始學習
廣告
© . All rights reserved.