New 關鍵詞的三種用法 C#

       前段時間一個朋友問到New關鍵字有幾種用法,雖說在日常編程中經常用到這個小傢伙,但它到底有幾種用法還真沒有留意過,現將從網上總結出的資料記下以供同仁學習 -_-!

(1)new  運算符  用於創建對象和調用構造函數。
(2)new  修飾符  用於隱藏基類成員的繼承成員。
(3)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 修飾符修飾它。

 

請看下面的類:


 1 public class MyClass
 2 
 3 {
 4 
 5    public int x;
 6 
 7    public void Invoke() {}
 8 
 9 }
10 

在派生類中用 Invoke 名稱聲明成員會隱藏基類中的 Invoke 方法,即:


1 public class MyDerivedC : MyClass
2 
3 {
4 
5    new public void Invoke() {}
6 
7 }
8 

但是,因爲字段 x 不是通過類似名隱藏的,所以不會影響該字段。

 

通過繼承隱藏名稱採用下列形式之一:
1.引入類或結構中的常數、指定、屬性或類型隱藏具有相同名稱的所有基類成員。
2.引入類或結構中的方法隱藏基類中具有相同名稱的屬性、字段和類型。同時也隱藏具有相同簽名的所有基類方法。
3.引入類或結構中的索引器將隱藏具有相同名稱的所有基類索引器。
4.在同一成員上同時使用 new override 是錯誤的。

注意:在不隱藏繼承成員的聲明中使用 new 修飾符將生成警告。


示例

在該例中,基類 MyBaseC 和派生類 MyDerivedC 使用相同的字段名 x,從而隱藏了繼承字段的值。該例說明了 new 修飾符的使用。同時也說明了如何使用完全限定名訪問基類的隱藏成員。


 1 using System;
 2 
 3 public class MyBaseC
 4 
 5 {
 6 
 7    public static int x = 55;
 8 
 9    public static int y = 22;
10 
11 }
12 
13  
14 
15 public class MyDerivedC : MyBaseC
16 
17 {
18 
19    new public static int x = 100;   // Name hiding
20 
21    public static void Main()
22 
23    {
24 
25       // Display the overlapping value of x:
26 
27       Console.WriteLine(x);
28 
29  
30 
31       // Access the hidden value of x:
32 
33       Console.WriteLine(MyBaseC.x);
34 
35  
36 
37       // Display the unhidden member y:
38 
39       Console.WriteLine(y);
40 
41    }
42 
43 }
44 

輸出

100

55

22

如果移除 new 修飾符,程序將繼續編譯和運行,但您會收到以下警告:

 

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

如果嵌套類型正在隱藏另一種類型,如下例所示,也可以使用 new 修飾符修改此嵌套類型。

 

示例

在該例中,嵌套類 MyClass 隱藏了基類中具有相同名稱的類。該例不僅說明了如何使用完全限定名訪問隱藏類成員,同時也說明了如何使用 new 修飾符消除警告消息。


 1 using System;
 2 
 3 public class MyBaseC
 4 
 5 {
 6 
 7    public class MyClass
 8 
 9    {
10 
11       public int x = 200;
12 
13       public int y;
14 
15    }
16 
17 }
18 
19  
20 
21 public class MyDerivedC : MyBaseC
22 
23 {
24 
25    new public class MyClass   // nested type hiding the base type members
26 
27    {
28 
29      public int x = 100;
30 
31       public int y;
32 
33       public int z;
34 
35    }
36 
37  
38 
39    public static void Main()
40 
41    {
42 
43       // Creating object from the overlapping class:
44 
45       MyClass S1 = new MyClass();
46 
47  
48 
49       // Creating object from the hidden class:
50 
51       MyBaseC.MyClass S2 = new MyBaseC.MyClass();
52 
53  
54 
55       Console.WriteLine(S1.x);
56 
57       Console.WriteLine(S2.x);  
58 
59    }
60 
61 }
62 

輸出

100

200

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章