在 C# 中重写

来源:这里教程网 时间:2026-02-21 16:23:40 作者:

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

相关推荐