抽象方法和虚拟方法有什么区别?在哪些情况下,建议使用抽象方法或虚拟方法?哪一种是最好的方法?
当前回答
答案已经提供了很多次,但关于何时使用每一个的问题是设计时的决定。我认为,尝试将通用方法定义捆绑到不同的接口中,并将它们拉到适当抽象级别的类中是一种很好的做法。当最好定义一个实现一组简洁接口的非抽象类时,将一组通用的抽象和虚拟方法定义转储到一个类中会使该类不可实例化。一如既往,这取决于什么最适合您的应用程序特定需求。
其他回答
抽象函数“只是”签名,没有实现。它在接口中用于声明如何使用类。它必须在其中一个派生类中实现。
虚函数(实际上是方法)也是您声明的函数,应该在继承层次结构类之一中实现。
此类类的继承实例也继承实现,除非您在较低层次结构类中实现它。
我通过对以下课程(从其他答案)进行一些改进,使这一点更简单:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TestOO
{
class Program
{
static void Main(string[] args)
{
BaseClass _base = new BaseClass();
Console.WriteLine("Calling virtual method directly");
_base.SayHello();
Console.WriteLine("Calling single method directly");
_base.SayGoodbye();
DerivedClass _derived = new DerivedClass();
Console.WriteLine("Calling new method from derived class");
_derived.SayHello();
Console.WriteLine("Calling overrided method from derived class");
_derived.SayGoodbye();
DerivedClass2 _derived2 = new DerivedClass2();
Console.WriteLine("Calling new method from derived2 class");
_derived2.SayHello();
Console.WriteLine("Calling overrided method from derived2 class");
_derived2.SayGoodbye();
Console.ReadLine();
}
}
public class BaseClass
{
public void SayHello()
{
Console.WriteLine("Hello\n");
}
public virtual void SayGoodbye()
{
Console.WriteLine("Goodbye\n");
}
public void HelloGoodbye()
{
this.SayHello();
this.SayGoodbye();
}
}
public abstract class AbstractClass
{
public void SayHello()
{
Console.WriteLine("Hello\n");
}
//public virtual void SayGoodbye()
//{
// Console.WriteLine("Goodbye\n");
//}
public abstract void SayGoodbye();
}
public class DerivedClass : BaseClass
{
public new void SayHello()
{
Console.WriteLine("Hi There");
}
public override void SayGoodbye()
{
Console.WriteLine("See you later");
}
}
public class DerivedClass2 : AbstractClass
{
public new void SayHello()
{
Console.WriteLine("Hi There");
}
// We should use the override keyword with abstract types
//public new void SayGoodbye()
//{
// Console.WriteLine("See you later2");
//}
public override void SayGoodbye()
{
Console.WriteLine("See you later");
}
}
}
只有抽象类才能有抽象成员。从抽象类继承的非抽象类必须重写其抽象成员。抽象成员是隐式虚拟的。抽象成员不能提供任何实现(抽象在某些语言中称为纯虚拟)。
抽象函数(方法):
● 抽象方法是用关键字abstract声明的方法。
● 它没有身体。
● 它应该由派生类实现。
● 如果方法是抽象的,那么类应该是抽象的。
虚拟函数(方法):
● 虚方法是用关键字virtual声明的方法,它可以通过使用override关键字由派生类方法重写。
● 是否重写它取决于派生类。
从面向对象的常规视图:关于抽象方法:当你把一个抽象方法放在父类中时,实际上你在对子类说:嘿,注意你有一个这样的方法签名。如果你想使用它,你应该实现你自己的!关于虚拟函数:当你在父类中放置一个虚拟方法时,你会对派生类说:嘿,这里有一个功能可以为你做些什么。如果这对你有用,就使用它。如果没有,重写它并实现你的代码,甚至你可以在代码中使用我的实现!这是关于通用OO中这两个概念之间不同的一些哲学