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

遮蓋

遮蓋也稱為方法隱藏。在遮蓋中,父類的方法可以使用於子類,而不使用 override 關鍵字。子類有其自己的版本,具有同樣的功能。

使用 new 關鍵字進行遮蓋,建立基本類函式的自己的版本。

讓我們來看一個示例 −

示例

using System;
using System.Collections.Generic;

class Demo {
   public class Parent {
      public string Display() {
         return "Parent Class!";
      }
   }
   
   public class Child : Parent {
      public new string Display() {
         return "Child Class!";
      }
   }

   static void Main(String[] args) {
      Child child = new Child();
      Console.WriteLine(child.Display());
   }
}

更新於: 21-Jun-2020

2K+ 瀏覽量

開啟你的 職業生涯

完成課程,獲得認證

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