标签:
转自MSDN:https://msdn.microsoft.com/zh-cn/library/435f1dw2.aspx
在用作修饰符时,new关键字可以显式的隐藏从基类继承的成员。隐藏继承的成员时,该成员的派生版本将替换基类版本。虽然可以不使用new修饰符的情况下隐藏成员,但会生成警告。如果使用new显示隐藏成员,则会取消此警告,并记录要替换为派生版本这一事实。
若要隐藏继承的成员,请使用相同名称在派生类中声明该成员,并使用new修饰符修饰该成员。例如:
1 public class BaseC
2 {
3 public int x;
4 public void Invoke() { }
5 }
6 public class DerivedC : BaseC
7 {
8 new public void Invoke() { }
9 }
在此示例中,DerivedC.Invoke隐藏了BaseC.Invoke。字段x不受影响,因为它没有被类似名称的字段隐藏。
通过继承隐藏名称采用下列形式之一:
对同一成员同时使用new和override是错误的做法,因为这两个修饰符的含义互斥。new修饰符会用同样的名称创建一个新成员并使原始成员变为隐藏的。override修饰符会扩展继承成员的实现。
在不隐藏继承成员的声明中使用new修饰符将会生成警告。
示例
在该例中,基类BaseC和派生类DerivedC使用相同的字段名x,从而隐藏了继承字段的值。该实例演示了new修饰符的用法。另外还演示了如何使用完全限定名访问基类的隐藏成员。
1 public class BaseC
2 {
3 public static int x = 55;
4 public static int y = 22;
5 }
6
7 public class DerivedC : BaseC
8 {
9 // Hide field ‘x‘.
10 new public static int x = 100;
11
12 static void Main()
13 {
14 // Display the new value of x:
15 Console.WriteLine(x);
16
17 // Display the hidden value of x:
18 Console.WriteLine(BaseC.x);
19
20 // Display the unhidden member y:
21 Console.WriteLine(y);
22 }
23 }
24 /*
25 Output:
26 100
27 55
28 22
29 */
在此示例中,嵌套类隐藏了基类中同名的类。此示例演示了如何使用new修饰符来消除警告消息,以及如何使用完全限定名来访问隐藏的类成员。
1 public class BaseC
2 {
3 public class NestedC
4 {
5 public int x = 200;
6 public int y;
7 }
8 }
9
10 public class DerivedC : BaseC
11 {
12 // Nested type hiding the base type members.
13 new public class NestedC
14 {
15 public int x = 100;
16 public int y;
17 public int z;
18 }
19
20 static void Main()
21 {
22 // Creating an object from the overlapping class:
23 NestedC c1 = new NestedC();
24
25 // Creating an object from the hidden class:
26 BaseC.NestedC c2 = new BaseC.NestedC();
27
28 Console.WriteLine(c1.x);
29 Console.WriteLine(c2.x);
30 }
31 }
32 /*
33 Output:
34 100
35 200
36 */
如果移除new修饰符,该程序仍可编译和运行,但您会收到以下警告:
The keyword new is required on ‘MyDerivedC.x‘ because it hides inherited member ‘MyBaseC.x‘
标签:
原文地址:http://www.cnblogs.com/imstrive/p/5664784.html