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.