C# 中的虛擬函式是什麼?


virtual 關鍵字可用於修改方法、屬性、索引器或事件。當你在一個類中定義了一個函式,而想要在已繼承的類中實現這個函式時,你可以使用虛擬函式。虛擬函式可以在不同的已繼承類中以不同的方式實現,而且在執行時會決定對這些函式的呼叫。

以下是一個虛擬函式

public virtual int area() { }

下面是一個演示如何使用虛擬函式的示例 −

示例

using System;

namespace PolymorphismApplication {
   class Shape {
      protected int width, height;
   
      public Shape( int a = 0, int b = 0) {
         width = a;
         height = b;
      }

      public virtual int area() {
         Console.WriteLine("Parent class area :");
         return 0;
      }
   }

   class Rectangle: Shape {
      public Rectangle( int a = 0, int b = 0): base(a, b) {

      }

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

   class Triangle: Shape {
      public Triangle(int a = 0, int b = 0): base(a, b) {
   }

   public override int area() {
      Console.WriteLine("Triangle class area:");
      return (width * height / 2);
   }
}

class Caller {
   public void CallArea(Shape sh) {
      int a;
      a = sh.area();
      Console.WriteLine("Area: {0}", a);
   }
}

class Tester {
   static void Main(string[] args) {
      Caller c = new Caller();
      Rectangle r = new Rectangle(10, 7);
      Triangle t = new Triangle(10, 5);

      c.CallArea(r);
      c.CallArea(t);
      Console.ReadKey();
   }
   }
}

更新時間:21-6-2020

4K+ 瀏覽量

開啟您的 職業

透過完成課程來獲得認證

開始學習
廣告
© . All rights reserved.