深入浅析c#静态多态性与动态多态性

2020-01-05 09:30:25丽君

面积: 70

当有一个定义在类中的函数需要在继承类中实现时,可以使用虚方法。虚方法是使用关键字 virtual 声明的。虚方法可以在不同的继承类中有不同的实现。对虚方法的调用是在运行时发生的。

动态多态性是通过 抽象类 和 虚方法 实现的。

下面的程序演示了这点:


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("父类的面积:");
     return 0;
   }
  }
  class Rectangle: Shape
  {
   public Rectangle( int a=0, int b=0): base(a, b)
   {
   }
   public override int area ()
   {
     Console.WriteLine("Rectangle 类的面积:");
     return (width * height); 
   }
  }
  class Triangle: Shape
  {
   public Triangle(int a = 0, int b = 0): base(a, b)
   {
   }
   public override int area()
   {
     Console.WriteLine("Triangle 类的面积:");
     return (width * height / 2); 
   }
  }
  class Caller
  {
   public void CallArea(Shape sh)
   {
     int a;
     a = sh.area();
     Console.WriteLine("面积: {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 类的面积:
面积:70
Triangle 类的面积:
面积:25

总结

以上所述是小编给大家介绍的c#静态多态性与动态多态性,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对ASPKU网站的支持!