C# 中的虛函數和抽象函數有什麼不同?

WBOY
發布: 2023-08-29 10:37:05
轉載
729 人瀏覽過

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
登入後複製

以上是C# 中的虛函數和抽象函數有什麼不同?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:tutorialspoint.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!