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学习者快速成长!