什麼是 C# 中的編譯時多型性?


多型性可以是靜態的或動態的。在靜態多型性中,在編譯時確定對函式的響應。在動態多型性中,它在執行時確定。

在編譯時將函式與一個物件連結叫做早期繫結。它也稱為靜態繫結。C# 為實現靜態多型性提供了兩種技術。它們是函式過載和運算子過載。

在函式過載中,可以在同一範圍內對同一函式名稱擁有多個定義。函式的定義必須根據引數列表中的型別和/或引數數量而有所不同。

以下是展示如何在 C# 中實現函式過載的例子 −

示例

 即時演示

using System;

namespace PolymorphismApplication {
   class Printdata {
      void print(int i) {
         Console.WriteLine("Printing int: {0}", i );
      }

      void print(double f) {
         Console.WriteLine("Printing float: {0}" , f);
      }

      void print(string s) {
         Console.WriteLine("Printing string: {0}", s);
      }

      static void Main(string[] args) {
         Printdata p = new Printdata();

         // Call print to print integer
         p.print(5);

         // Call print to print float
         p.print(500.263);

         // Call print to print string
         p.print("Hello C++");
         Console.ReadKey();
      }
   }
}

輸出

Printing int: 5
Printing float: 500.263
Printing string: Hello C++

更新日期: 2020 年 6 月 20 日

2K+ 瀏覽次數

開始你的 事業

完成課程認證

開始
廣告
© . All rights reserved.