重写、隐藏基类(new, override) 重写、隐藏基类(new, override)的方法

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

重写、隐藏基类(new, override) 重写、隐藏基类(new, override)的方法

  2021-03-18 我要评论
想了解重写、隐藏基类(new, override)的方法的相关内容吗,在本文为您仔细讲解重写、隐藏基类(new, override)的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:重写,隐藏,new,override,下面大家一起来学习吧。

复制代码 代码如下:

public class Father
    {
        public void Write() {
            Console.WriteLine("父");
        }
    }

    public class Mother
    {
        public virtual void Write()
        {
            Console.WriteLine("母");
        }
    }

    public class Boy : Father
    {
        public new void Write()
        {
            Console.WriteLine("子");
        }
    }

    public class Girl : Mother
    {
        public override void Write()
        {
            Console.WriteLine("女");
        }
    }


复制代码 代码如下:

static void Main(string[] args)
        {
            Father father = new Boy();
            father.Write();

            Boy boy = new Boy();
            boy.Write();


            Mother mother = new Mother();
            mother.Write();

            Girl girl = new Girl();
            girl.Write();

            Console.ReadLine();
        }


输出:




添加调用父方法:

复制代码 代码如下:

public class Boy : Father
    {
        public new void Write()
        {
            base.Write();
            Console.WriteLine("子");
        }
    }

    public class Girl : Mother
    {
        public override void Write()
        {
            base.Write();
            Console.WriteLine("女");
        }
    }


输出:






可见,在程序运行结果上new 和override是一样的。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们