C# 中虛擬函式和抽象函式有什麼區別?
抽象方法不提供實現,並且強制派生類重寫該方法。它在抽象類中宣告。抽象方法僅具有方法定義。
虛擬函式具有實現,這與抽象方法不同,並且可以存在於抽象類和非抽象類中。它為派生類提供了重寫它的選項。
虛擬函式
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();
}
}
}輸出
Rectangle class area Area: 70 Triangle class area: 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP