在 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

575 次瀏覽

事業 起航

完成課程即可獲得認證

開始
廣告