重写、隐藏基类(new, override)的方法_C#教程-查字典教程网
重写、隐藏基类(new, override)的方法
重写、隐藏基类(new, override)的方法
发布时间:2016-12-28 来源:查字典编辑
摘要:复制代码代码如下:publicclassFather{publicvoidWrite(){Console.WriteLine("父");}}...

复制代码 代码如下:

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是一样的。

相关阅读
推荐文章
猜你喜欢
附近的人在看
推荐阅读
拓展阅读
  • 大家都在看
  • 小编推荐
  • 猜你喜欢
  • 最新C#教程学习
    热门C#教程学习
    编程开发子分类