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 年 6 月 21 日

472 次瀏覽

開啟你的 事業

完成課程,獲得認證

開始
廣告
© . All rights reserved.