C# 中的函数重写和方法隐藏有什么区别?

csharpprogrammingserver side programming更新于 2025/10/13 18:22:17

重写

重写是指定义特定于子类类型的行为,这意味着子类可以根据其需求实现父类方法。

让我们看一个实现重写的抽象类的示例。 −

示例

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

方法隐藏(Shadowing)

Shadowing 也称为方法隐藏。在隐藏过程中,无需使用 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());
   }
}

相关文章