什麼是 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

更新於: 2020-06-20

2000+ 瀏覽量

開啟你的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.