在 C# 中,什麼是執行時多型性?


執行時多型性具有方法覆蓋,也稱為動態繫結或後期繫結。它是透過 抽象類 和 虛擬函式 實現的。

抽象類

抽象 類包含抽象方法,這些方法由派生類實現。

讓我們看一下抽象類的一個示例,它實現了執行時多型性——

示例

 現場演示

using System;

namespace PolymorphismApplication {
   abstract class Shape {
      public abstract int area();
   }

   class Rectangle: Shape {
      private int length;
      private int width;

      public Rectangle( int a = 0, int b = 0) {
         length = a;
         width = b;
      }

      public override int area () {
         Console.WriteLine("Rectangle class area :");
            return (width * length);
      }
   }

   class RectangleTester {
      static void Main(string[] args) {
         Rectangle r = new Rectangle(10, 7);
         double a = r.area();
         Console.WriteLine("Area: {0}",a);
         Console.ReadKey();
      }
   }
}

示例

Rectangle class area :
Area: 70

虛擬函式

當你有一個在類中定義的函式,並且要將其實現到繼承類中時,可以使用 虛擬 函式。虛擬函式可以在不同的繼承類中以不同的方式實現,對這些函式的呼叫將在執行時決定。

更新日期:2020-03-18

2K+ 瀏覽量

開啟你的 職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.