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();
      }
   }
}

更新於: 2020-06-21

472 次瀏覽

Kickstart 您的 職業

完成課程並獲得證書

開始
廣告
© . All rights reserved.