C# 中的虚函数是什么?
csharpprogrammingserver side programming更新于 2025/10/13 12:22:17
virtual 关键字在修饰方法、属性、索引器或事件时非常有用。当您在类中定义了一个函数,并希望在继承类中实现它时,可以使用虚函数。不同的继承类中,虚函数的实现方式可能不同,这些函数的调用方式将在运行时决定。
以下是一个虚函数
public virtual int area() { }
以下示例展示了如何使用虚函数 −
示例
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();
}
}
}

