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 這些運算子不能過載 |
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP