4个程序看C#中隐藏与覆盖的区别
刚刚学习C#,书才看了两章,发点东西,高手勿笑override 和 new 对继承的效果
program 1:
程序代码:
using System; class A { private int version=3; public void output() { Console.WriteLine("A:"+version); } } class B:A { private int version=4; public void output() { Console.WriteLine("B:"+version); } } class test { static void Main() { A a1=new A(); A a2=new B(); B b2=new B(); a1.output(); a2.output(); b2.output(); } }
program 1 执行结果:
编译有警告:
jctest.cs(14,14): warning CS0108: 'B.output()' hides inherited member
'A.output()'. Use the new keyword if hiding was intended.
jctest.cs(5,15): (Location of symbol related to previous warning)
因为,B隐藏了A的方法,但是没有用 new 显示的声明隐藏。
执行结果:
A:3
A:3
B:4
program 2:
程序代码:
using System; class A { private int version=3; public void output() { Console.WriteLine("A:"+version); } } class B:A { private int version=4; public new void output() { Console.WriteLine("B:"+version); } } class test { static void Main() { A a1=new A(); A a2=new B(); B b2=new B(); a1.output(); a2.output(); b2.output(); } }
program 2 执行结果:
编译成功,无警告、无报错。
执行结果:
A:3
A:3
B:4
program 3:
程序代码:
using System; class A { private int version=3; public void output() { Console.WriteLine("A:"+version); } } class B:A { private int version=4; public override void output() { Console.WriteLine("B:"+version); } } class test { static void Main() { A a1=new A(); A a2=new B(); B b2=new B(); a1.output(); a2.output(); b2.output(); } }编译报错:覆盖的函数必须是有virtual或者override修饰的函数。
program 4:
程序代码:
using System; class A { private int version=3; public virtual void output() { Console.WriteLine("A:"+version); } } class B:A { private int version=4; public override void output() { Console.WriteLine("B:"+version); } } class test { static void Main() { A a1=new A(); A a2=new B(); B b2=new B(); a1.output(); a2.output(); b2.output(); } }编译成功,无警告、无报错。
执行结果:
A:3
B:4
B:4
[ 本帖最后由 观星 于 2011-2-23 11:48 编辑 ]