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

Learn C# in-depth with real-world projects through our C# certification course. Enroll and become a certified expert to boost your career.

示例

Rectangle class area :
Area: 70

虚拟函数

当你在一个类中定义了一个你希望在继承类中实现的函数时,你使用了 虚拟 函数。虚拟函数可以在不同的继承类中以不同的方式实现,对这些函数的调用将在运行时决定。

更新于: 18-Mar-2020

2K+ 浏览量

开启您的 职业生涯

完成课程认证

开始
广告