C# 中的动态绑定是什么?


在静态多态中,函数响应由编译时确定。在动态多态中,它由运行时决定。动态多态是我们所说的动态绑定。

动态多态由抽象类和虚拟函数实现。以下示例展示了动态多态的一个示例 -

示例

 实况演示

using System;

namespace PolymorphismApplication {
   class Shape {
      protected int width, height;

      public Shape( int a = 0, int b = 0) {
         width = a;
         height = b;
      }

      public virtual int area() {
         Console.WriteLine("Parent class area :");
         return 0;
      }
   }

   class Rectangle: Shape {
      public Rectangle( int a = 0, int b = 0): base(a, b) {}
      public override int area () {
         Console.WriteLine("Rectangle class area :");
         return (width * height);
      }
   }

   class Triangle: Shape {
      public Triangle(int a = 0, int b = 0): base(a, b) {}
      public override int area() {
         Console.WriteLine("Triangle class area :");
         return (width * height / 2);
      }
   }

   class Caller {
      public void CallArea(Shape sh) {
         int a;
         a = sh.area();
         Console.WriteLine("Area: {0}", a);
      }
   }

   class Tester {
      static void Main(string[] args) {
         Caller c = new Caller();
         Rectangle r = new Rectangle(10, 7);
         Triangle t = new Triangle(10, 5);
         c.CallArea(r);
         c.CallArea(t);
         Console.ReadKey();
      }
   }
}

输出

Rectangle class area :
Area: 70
Triangle class area :
Area: 25

更新于: 20-6-2020

1K+ 浏览量

开启你的职业生涯

完成课程获取认证

开始
广告
© . All rights reserved.