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("父类区域:");
return 0;
}
}
class Rectangle: Shape {
public Rectangle( int a = 0, int b = 0): base(a, b) {}
public override int area () {
Console.WriteLine("矩形类面积:");
return (width * height);
}
}
class Triangle: Shape {
public Triangle(int a = 0, int b = 0): base(a, b) {}
public override int area() {
Console.WriteLine("三角班区:");
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();
}
}
}输出结果矩形类面积: Area: 70 三角班区: Area: 25