抽象方法和虚拟方法有什么区别?在哪些情况下,建议使用抽象方法或虚拟方法?哪一种是最好的方法?
当前回答
抽象方法是一种必须实现才能生成具体类的方法。声明在抽象类中(任何具有抽象方法的类都必须是抽象类),并且必须在具体类中实现。
虚拟方法是一种可以在派生类中使用重写重写的方法,替换超类中的行为。如果不覆盖,则获得原始行为。如果你这样做,你总会得到新的行为。这与不能重写但可以隐藏原始方法的非虚拟方法相反。这是使用新修改器完成的。
请参见以下示例:
public class BaseClass
{
public void SayHello()
{
Console.WriteLine("Hello");
}
public virtual void SayGoodbye()
{
Console.WriteLine("Goodbye");
}
public void HelloGoodbye()
{
this.SayHello();
this.SayGoodbye();
}
}
public class DerivedClass : BaseClass
{
public new void SayHello()
{
Console.WriteLine("Hi There");
}
public override void SayGoodbye()
{
Console.WriteLine("See you later");
}
}
当我实例化DerivedClass并调用SayHello或SayGoodbye时,我会得到“Hi There”和“See you later”。如果我打电话给HelloGoodbye,我会收到“你好”和“再见”。这是因为SayGoodbye是虚拟的,可以被派生类替换。SayHello只是隐藏的,所以当我从基类调用它时,我会得到原始方法。
抽象方法是隐式虚拟的。它们定义了必须存在的行为,更像是一个接口。
其他回答
抽象函数没有实现,只能在抽象类上声明。这迫使派生类提供实现。
虚拟函数提供默认实现,它可以存在于抽象类或非抽象类上。
例如:
public abstract class myBase
{
//If you derive from this class you must implement this method. notice we have no method body here either
public abstract void YouMustImplement();
//If you derive from this class you can change the behavior but are not required to
public virtual void YouCanOverride()
{
}
}
public class MyBase
{
//This will not compile because you cannot have an abstract method in a non-abstract class
public abstract void YouMustImplement();
}
抽象方法是一种必须实现才能生成具体类的方法。声明在抽象类中(任何具有抽象方法的类都必须是抽象类),并且必须在具体类中实现。
虚拟方法是一种可以在派生类中使用重写重写的方法,替换超类中的行为。如果不覆盖,则获得原始行为。如果你这样做,你总会得到新的行为。这与不能重写但可以隐藏原始方法的非虚拟方法相反。这是使用新修改器完成的。
请参见以下示例:
public class BaseClass
{
public void SayHello()
{
Console.WriteLine("Hello");
}
public virtual void SayGoodbye()
{
Console.WriteLine("Goodbye");
}
public void HelloGoodbye()
{
this.SayHello();
this.SayGoodbye();
}
}
public class DerivedClass : BaseClass
{
public new void SayHello()
{
Console.WriteLine("Hi There");
}
public override void SayGoodbye()
{
Console.WriteLine("See you later");
}
}
当我实例化DerivedClass并调用SayHello或SayGoodbye时,我会得到“Hi There”和“See you later”。如果我打电话给HelloGoodbye,我会收到“你好”和“再见”。这是因为SayGoodbye是虚拟的,可以被派生类替换。SayHello只是隐藏的,所以当我从基类调用它时,我会得到原始方法。
抽象方法是隐式虚拟的。它们定义了必须存在的行为,更像是一个接口。
抽象函数(方法):
● 抽象方法是用关键字abstract声明的方法。
● 它没有身体。
● 它应该由派生类实现。
● 如果方法是抽象的,那么类应该是抽象的。
虚拟函数(方法):
● 虚方法是用关键字virtual声明的方法,它可以通过使用override关键字由派生类方法重写。
● 是否重写它取决于派生类。
C#中没有调用虚拟类的内容。
对于函数
抽象函数仅具有签名,驱动器类应使用功能重写。虚拟功能将保留驱动器类根据需要可以覆盖或不覆盖的部分功能
你可以决定你的要求。
抽象方法没有实现。它在父类中声明。子类负责实现该方法。
虚拟方法应该在父类中有一个实现,它有助于子类选择是使用父类的该实现,还是为子类中的该方法自己有一个新的实现。