C#--virtual,abstract,override,new,sealed

virtual:使用此关键字,可以使其在派生类中被重写.

abstract:抽象方法,由子类重写,或继续为抽象方法存在,并由其子子类实现.

override: 重写父类方法,属性,或事件的抽象实现或虚方法.

new:显式隐藏从父类继承的成员.

 

后台代码:

public abstract class Animal
{
    public abstract void Eat();

    public virtual void Sleep()
    {
        HttpContext.Current.Response.Write("动物正在睡觉!<hr/>");
    }
}

public class Horse : Animal
{
    public override void Eat()
    {
        HttpContext.Current.Response.Write("马在吃草!<br/>");
    }

    public override void Sleep()
    {
        HttpContext.Current.Response.Write("马是站着睡觉!<hr/>");
    }
}

public class Cat : Animal
{
    public override void Eat()
    {
        HttpContext.Current.Response.Write("猫在吃食!<br/>");
    }

    public new void Sleep()
    {
        HttpContext.Current.Response.Write("猫是趴着睡觉的!<hr/>");
    }
}
前台调用 效果
    protected void Page_Load(object sender, EventArgs e)
    {
        Animal an1 = new Horse();
        an1.Eat();
        an1.Sleep();

        Animal an2 = new Cat();
        an2.Eat();
        an2.Sleep();

        Horse an3 = new Horse();
        an3.Eat();
        an3.Sleep();

        Cat an4 = new Cat();
        an4.Eat();
        an4.Sleep();
    }
image

 

补充:

当sealed修饰方法时,sealed必须与override一起使用.

sealed将使您能够允许类从您的类继承,并防止它们重写特定的虚方法或虚属性

public class Cat : Animal
{
    public sealed override void Eat()
    {
        HttpContext.Current.Response.Write("猫在吃食!<br/>");
    }

    public new void Sleep()
    {
        HttpContext.Current.Response.Write("猫是趴着睡觉的!<hr/>");
    }
}

public class LitCat : Cat
{
    public new void Sleep()
    {
        HttpContext.Current.Response.Write("猫是趴着睡觉的!<hr/>");
    }
}

此时,在LitCat类中,就不会出现override Eat方法了.

posted @ 2009-07-02 10:36  Localhost  阅读(451)  评论(0编辑  收藏  举报