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();
    }
C#--virtual,abstract,override,new,sealed

 

补充:

当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方法了.

相关文章:

  • 2022-12-23
  • 2021-11-15
  • 2022-01-05
  • 2022-03-09
  • 2021-09-07
  • 2022-12-23
  • 2022-01-10
  • 2022-12-23
猜你喜欢
  • 2021-08-04
  • 2021-07-16
  • 2022-02-18
  • 2021-05-24
相关资源
相似解决方案