首頁  >  文章  >  後端開發  >  C#中什麼是重載?

C#中什麼是重載?

WBOY
WBOY轉載
2023-09-06 22:17:02786瀏覽

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

運算子重載

重載運算子是具有特殊名稱的函數,關鍵字運算子後面跟著所定義的運算子的符號。

下面顯示了哪些運算子可以重載以及哪些運算子可以重載不能超載-

5
#Sr.No 運算符與描述
1 # , - , !, ~, , --

這些一元運算子採用一個操作數並且可以重載。

2 、-、*、/、%

這些二元運算符採用一個操作數並且可以重載。

3 ==、!=、、=

比較運算子可以重載。

4 &&、||

條件邏輯運算子不能直接重載。

=、-=、*=、/=、%=

賦值運算子不能重載。

6 =, ., ?:, -

#這些運算子不能重載

#

以上是C#中什麼是重載?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除