C#中的過載是什麼?


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

運算子過載

過載的運算子是具有特殊名稱的函式,關鍵字 `operator` 後跟被定義的運算子的符號。

以下是可以過載和不能過載的運算子:

序號運算子和描述
1+, -, !, ~, ++, --
這些一元運算子接受一個運算元,可以過載。
2+, -, *, /, %
這些二元運算子接受一個運算元,可以過載。
3==, !=, <, >, <=, >=
比較運算子可以過載。
4&&, ||
條件邏輯運算子不能直接過載。
5+=, -=, *=, /=, %=
賦值運算子不能過載。
6=, ., ?:, -<, new, is, sizeof, typeof
這些運算子不能過載

更新於:2020年6月20日

2K+ 次瀏覽

啟動你的職業生涯

完成課程後獲得認證

開始學習
廣告