古詩詞大全網 - 個性簽名 - c#裏面的override和new究竟有什麽區別啊

c#裏面的override和new究竟有什麽區別啊

override是重載所繼承的類型方法的 而被繼承的類方法必須加virtual 才可以被重載

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