C#之new修饰符

转自MSDN:https://msdn.microsoft.com/zh-cn/library/435f1dw2.aspx

 

 new隐藏基类成员

在用作修饰符时,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'

 

new约束

当泛型类创建类型的新实例,请将 new 约束应用于类型参数,如下面的示例所示:

1 class ItemFactory<T> where T : new()
2 {
3     public T GetNewItem()
4     {
5         return new T();
6     }
7 }

 

posted @ 2016-07-12 20:31  imstrive  阅读(4714)  评论(0编辑  收藏  举报