1.隐藏基类成员
派生类不能删除它继承的任何成员,但可以隐藏它。
1.1 要隐藏一个继承的数据成员,需要声明一个新的相同类型的成员,并使用相同的名称。
1.2 通过在派生类中声明新的带有相同的签名的函数成员,可以隐藏基类的函数成员。(不包含返回值类型)。
1.3 使用new修饰符隐藏基类成员。(也可以隐藏静态成员)
举例说明 new 和Override的区别
1.4使用override 声明Print
1 class MyBaseClass 2 3 { 4 5 vittual public void Print(){Console.WriteLine("this is the base class");} 6 7 } 8 9 class MyDerivedClass : MybaseClass 10 11 { 12 13 override public void Print(){Console.WriteLine("this is the derived class");} 14 15 } 16 17 class Progrem 18 19 { 20 21 static void Main() 22 23 { 24 25 MyDerivedClass derived=new MyDerivedClass(); 26 27 MyBaseClass mybc=(MybaseClass)derived; 28 29 derived.Print(); 30 31 mybc.Print(); 32 33 } 34 35 }
输出结果为:
this is the derived class
this is the derived class
1.5使用new声明Print.
1 class MyBaseClass 2 3 { 4 5 vittual public void Print(){Console.WriteLine("this is the base class");} 6 7 } 8 9 class MyDerivedClass : MybaseClass 10 11 { 12 13 new public void Print(){Console.WriteLine("this is the derived class");} 14 15 } 16 17 class Progrem 18 19 { 20 21 static void Main() 22 23 { 24 25 MyDerivedClass derived=new MyDerivedClass(); 26 27 MyBaseClass mybc=(MybaseClass)derived; 28 29 derived.Print(); 30 31 mybc.Print(); 32 33 } 34 35 }
输出结果为:
this is the derived class
this is the base class