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

影射

影射也稱為方法隱藏。在影射中,可以使用父類的函式而不使用重寫關鍵詞。子類有自己的相同函式的版本。

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

更新於: 2020 年 6 月 21 日

2000+ 檢視

啟動您的職業生涯

完成課程,透過認證

開始
廣告
© . All rights reserved.