C# 继承 测试

1、方法重写  
class Parent { public void m1() { m2(); } public virtual void m2() { Console.WriteLine("I am Parent."); } } class Child : Parent { public override void m2() { Console.WriteLine("I am Child."); } } class Program { static void Main(string[] args) { Parent parent = new Parent(); parent.m1(); //I am parent parent.m2(); //I am parent Child child = new Child(); child.m1(); //I am Child child.m2(); //I am child Parent parent2 = new Child(); parent2.m1(); //I am Child parent2.m2(); //I am Child } }

 2、方法隐藏

 1     class Parent
 2     {
 3         public void m1()
 4         {
 5             m2();
 6         }
 7         public void m2()
 8         {
 9             Console.WriteLine("I'm parent");
10         }
11     }
12     class Child : Parent
13     {
14         public new void m2()
15         {
16             Console.WriteLine("I'm child");
17         }
18     }
19     
20    
21     class Program
22     {
23         
24         static void Main(string[] args)
25         {
26             Parent parent = new Parent();
27             parent.m1();    //I'm parent
28             parent.m2();    //I'm parent
29 
30             Child child = new Child();
31             child.m1();     //I'm parent
32             child.m2();     //I'm child
33 
34             Parent child2 = new Child();
35             child2.m1();    //I'm parent
36             child2.m2();    //I'm parent
37 
38         }   
39     }

 

posted @ 2022-10-09 20:16  竹楼风雨声  阅读(15)  评论(0编辑  收藏  举报