zoukankan      html  css  js  c++  java
  • 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方法了.

  • 相关阅读:
    61. Rotate List
    60. Permutation Sequence
    59. Spiral Matrix II ***
    58. Length of Last Word
    57. Insert Interval
    328. Odd Even Linked List
    237. Delete Node in a Linked List
    关于找List的中间Node
    234. Palindrome Linked List
    203. Remove Linked List Elements *
  • 原文地址:https://www.cnblogs.com/oneword/p/1515279.html
Copyright © 2011-2022 走看看