抽象方法和虚拟方法有什么区别?在哪些情况下,建议使用抽象方法或虚拟方法?哪一种是最好的方法?
当前回答
抽象函数不能具有功能。你基本上是说,任何子类都必须给出自己版本的这个方法,但是它太通用了,甚至无法在父类中实现。
一个虚拟函数,基本上就是说,看,这里的功能对于子类来说可能不够好,也可能不够好。因此,如果它足够好,请使用此方法,如果不好,请重写我,并提供您自己的功能。
其他回答
必须始终重写抽象函数。
因此:
抽象函数-当继承者必须提供自己的实现时虚拟-由继承人决定
抽象方法总是虚拟的。它们无法实现。
这是主要的区别。
基本上,如果您有一个虚拟方法的“默认”实现,并且希望允许后代更改其行为,那么您将使用该方法。
使用抽象方法,可以强制后代提供实现。
抽象方法:当类包含抽象方法时,该类必须声明为抽象的。抽象方法没有实现,因此派生自该抽象类的类必须为该抽象方法提供实现。
虚拟方法:类可以具有虚拟方法。虚拟方法有一个实现。当从具有虚拟方法的类继承时,可以重写虚拟方法并提供额外的逻辑,或者用自己的实现替换逻辑。
何时使用什么:在某些情况下,您知道某些类型应该有一个特定的方法,但您不知道该方法应该有什么实现。在这种情况下,您可以创建包含具有此签名的方法的接口。然而,如果您有这样的情况,但您知道该接口的实现者也将有另一个通用方法(您已经可以为其提供实现),那么您可以创建一个抽象类。然后,这个抽象类包含抽象方法(必须重写)和另一个包含“公共”逻辑的方法。
如果您有一个可以直接使用的类,但您希望继承者能够更改某些行为,则应使用虚拟方法,尽管这不是强制性的。
抽象函数“只是”签名,没有实现。它在接口中用于声明如何使用类。它必须在其中一个派生类中实现。
虚函数(实际上是方法)也是您声明的函数,应该在继承层次结构类之一中实现。
此类类的继承实例也继承实现,除非您在较低层次结构类中实现它。
我通过对以下课程(从其他答案)进行一些改进,使这一点更简单:
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");
}
}
}