抽象方法不提供实现,而是强制派生类重写该方法。它在抽象类下声明。抽象方法只有方法定义
虚拟方法具有一个实现,与Abstract方法不同,它可以存在于abstract和non-abstract类中。它为派生类提供了覆盖它的选项。
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("家长课区:"); 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("三角形类区域:"); 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 三角形类区域: Area: 25
C#中的abstract关键字用于抽象类和抽象函数。C#中的抽象类包括抽象和非抽象方法。
以下是C#中抽象类中抽象函数的示例-
using System; public abstract class Vehicle { public abstract void display(); } public class Bus : Vehicle { public override void display() { Console.WriteLine("Bus"); } } public class Car : Vehicle { public override void display() { Console.WriteLine("Car"); } } public class Motorcycle : Vehicle { public override void display() { Console.WriteLine("Motorcycle"); } } public class MyClass { public static void Main() { Vehicle v; v = new Bus(); v.display(); v = new Car(); v.display(); v = new Motorcycle(); v.display(); } }
输出结果
Bus Car Motorcycle