我是靠谱客的博主 爱笑可乐,这篇文章主要介绍C#学习-方法隐藏(new关键字)&&重写(virtual&override),现在分享给大家,希望可以做个参考。

隐藏:

using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;

namespace _TBD_2020814Test
{
    class Animal {
        public void Show()
        {
            Console.WriteLine("Animal Show!");
        }
    }
    class Cat : Animal {
        public new void Show()    //方法中使用关键字new,子类新写的方法把父类的方法隐藏起来
        {
            Console.WriteLine("Cat Show!");
        }
    }
    class Dog : Animal { }
    class Hashiqi : Dog { }
    class Program
    {
        static void Main(string[] args)
        {
            Cat c = new Cat();
            c.Show();//Cat Show
            Animal a = new Cat();
            a.Show();//Animal Show,是调用子类Cat中继承的

        }
    }
}

重写:

using System;
using System.CodeDom;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;

namespace _TBD_2020814Test
{
    class Animal {
        public virtual  void Show()//使用virtual关键字,虚方法
        {
            Console.WriteLine("Animal Show!");
        }
    }
    class Cat : Animal {
        public override void Show()    //方法中使用关键字override,子类修改父类的方法
        {
            Console.WriteLine("Cat Show!");
        }
    }
    class Jiafei : Cat {
        public override void Show()    //override可被继续重写
        {
            Console.WriteLine("Jiafei Show!");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Cat c = new Cat();
            c.Show();//Cat Show
            Animal a = new Cat();
            a.Show();//Cat Show,是调用子类Cat中继承的
            Jiafei j = new Jiafei();//Jiafei Show
            j.Show();
        }
    }
}

 

最后

以上就是爱笑可乐最近收集整理的关于C#学习-方法隐藏(new关键字)&&重写(virtual&override)的全部内容,更多相关C#学习-方法隐藏(new关键字)&&重写(virtual&override)内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(91)

评论列表共有 0 条评论

立即
投稿
返回
顶部