new 修飾符
在用作修飾符時,new 關鍵字可以顯式隱藏從基類繼承的成員。隱藏繼承的成員時,該成員的派生版本將替換基類版本。雖然可以在不使用 new 修飾符的情況下隱藏成員,但會生成警告。如果使用 new 顯式隱藏成員,則會取消此警告,並記錄要替換爲派生版本這一事實。
若要隱藏繼承的成員,請使用相同名稱在派生類中聲明該成員,並使用 new 修飾符修飾該成員。
// cs_modifier_new.cs
// The new modifier.
using System;
public class BaseC
{
public static int x = 55;
public static int y = 22;
}
public class DerivedC : BaseC
{
// Hide field 'x'.
new public static int x = 100;
static void Main()
{
// Display the new value of x:
Console.WriteLine(x);
// Display the hidden value of x:
Console.WriteLine(BaseC.x);
// Display the unhidden member y:
Console.WriteLine(y);
}
}
new 約束
new 約束指定泛型類聲明中的任何類型參數都必須有公共的無參數構造函數。當泛型類創建類型的新實例時,將此約束應用於類型參數
class ItemFactory<T> where T : new()
{
public T GetNewItem()
{
return new T();
}
}
new 運算符
用於創建對象和調用構造函數
還可用於創建匿名類型的實例:
var query = from cust in customers
select new {Name = cust.Name, Address = cust.PrimaryAddress};
|
new 運算符還用於調用值類型的默認構造函數