抽象方法与虚方法(转)
1. 虚方法必须有实现部分,抽象方法没有提供实现部分,抽象方法是一种强制派生类覆盖的方法,否则派生类将不能被实例化。如:
public abstract class Animal
{
public abstract void Sleep();
public abstract void Eat();
}
//虚方法
public class Animal
{
public virtual void Sleep(){}
public virtual void Eat(){}
}
2. 抽象方法只能在抽象类中声明,虚方法不是。其实如果类包含抽象方法,那么该类也是抽象的,也必须声明为抽象的。如:
{
public abstract void Sleep();
public abstract void Eat();
}
编译器会报错:
Main.cs(10): 'VSTest.Animal.Sleep()' is abstract but it is contained in nonabstract class 'VSTest.Animal'
Main.cs(11): 'VSTest.Animal.Eat()' is abstract but it is contained in nonabstract class 'VSTest.Animal'
3. 抽象方法必须在派生类中重写,这一点跟接口类似,虚方法不必。如:
{
public abstract void Sleep();
public abstract void Eat();
}
public class Cat : Animal
{
public override void Sleep()
{
Console.WriteLine( "Cat is sleeping" );
}
// we need implement Animal.Eat() here
}
编译器会报错:Main.cs(14): 'VSTest.Cat' does not implement inherited abstract member 'VSTest.Animal.Eat()',因为我们没有实现抽象类中所有抽象方法。
---------------------------------------------------------------------------------------------------------------------------------------------------------------------
一个完整的虚方法的例子:
public class Base
{
public virtual void Method()
{
Console.WriteLine("Base:Method");
}
}
public class Derived : Base
{
public override void Method()
{
Console.WriteLine("Derived:Method");
}
}
class program
{
static void Main(string[] args)
{
Derived MyDerived = new Derived();
MyDerived.Method();
Console.ReadLine();
}
}
输出结果:Derived:Method
注意:1.可在派生类中以override覆盖此方法
2.不覆盖也可由对象调用,例如,去掉以下代码:
public override void Method()
{
Console.WriteLine("Derived:Method");
}
输出的结果是:Base:Method