C# - new关键字小结

C# 中,new 关键字可用作运算符或修饰符。

 

new 运算符   用于在堆上创建对象和调用构造函数。

new 修饰符   用于隐藏基类成员的继承成员。

 

new 运算符

1.用于创建对象和调用构造函数

例:Class_Test MyClass  = new Class_Test();

2.也用于为值类型调用默认的构造函数

例:int myInt = new int();

myInt 初始化为 0,它是 int 类型的默认值。该语句的效果等同于:int myInt = 0;

3.不能重载 new 运算符。

4.如果 new 运算符分配内存失败,则它将引发 OutOfMemoryException 异常。

 

new 修饰符

使用 new 修饰符显式隐藏从基类继承的成员。若要隐藏继承的成员,请使用相同名称在派生类中声明该成员,并用 new 修饰符修饰它。

 

请看下面的类:

 

public class MyClass

{

   public int x;

   public void Invoke() {}

}

在派生类中用 Invoke 名称声明成员会隐藏基类中的 Invoke 方法,即:

public class MyDerivedC : MyClass

{

   new public void Invoke() {}

}

但是,因为字段 x 不是通过类似名隐藏的,所以不会影响该字段。

 

通过继承隐藏名称采用下列形式之一:

1.引入类或结构中的常数、指定、属性或类型隐藏具有相同名称的所有基类成员。

2.引入类或结构中的方法隐藏基类中具有相同名称的属性、字段和类型。同时也隐藏具有相同签名的所有基类方法。

3.引入类或结构中的索引器将隐藏具有相同名称的所有基类索引器。

4.在同一成员上同时使用 new override 是错误的。

 

注意:在不隐藏继承成员的声明中使用 new 修饰符将生成警告。

 

示例

在该例中,基类 MyBaseC 和派生类 MyDerivedC 使用相同的字段名 x,从而隐藏了继承字段的值。该例说明了 new 修饰符的使用。同时也说明了如何使用完全限定名访问基类的隐藏成员。

using System;

public class MyBaseC

{

   public static int x = 55;

   public static int y = 22;

}

 

public class MyDerivedC : MyBaseC

{

   new public static int x = 100;   // Name hiding

   public static void Main ()

   {

      // Display the overlapping value of x:

      Console.WriteLine(x);

 

      // Access the hidden value of x:

      Console.WriteLine(MyBaseC.x);

 

      // Display the unhidden member y:

      Console.WriteLine(y);

   }

}

输出

100

55

22

如果移除 new 修饰符,程序将继续编译和运行,但您会收到以下警告:

 

The keyword new is required on 'MyDerivedC.x' because it hides inherited member 'MyBaseC.x'.

如果嵌套类型正在隐藏另一种类型,如下例所示,也可以使用 new 修饰符修改此嵌套类型。

 

示例

在该例中,嵌套类 MyClass 隐藏了基类中具有相同名称的类。该例不仅说明了如何使用完全限定名访问隐藏类成员,同时也说明了如何使用 new 修饰符消除警告消息。

using System;

public class MyBaseC

{

   public class MyClass

   {

      public int x = 200;

      public int y;

   }

}

 

public class MyDerivedC : MyBaseC

{

   new public class MyClass   // nested type hiding the base type members

   {

      public int x = 100;

      public int y;

      public int z;

   }

 

   public static void Main ()

   {

      // Creating object from the overlapping class:

      MyClass S1  = new MyClass();

 

      // Creating object from the hidden class:

      MyBaseC.MyClass S2 = new MyBaseC.MyClass();

 

      Console.WriteLine(S1.x);

      Console.WriteLine(S2.x);  

   }

}

输出

100

200

 

本文参考《MSDN Library – Visual Studio .NET 2003

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值