在 C# 中,new 關鍵字可用作運算符、修飾符或約束。
1)new 運算符:用於創建對象和調用構造函數。
2)new 修飾符:在用作修飾符時,new 關鍵字可以顯式隱藏從基類繼承的成員。
3)
new 約束:用於在泛型聲明中約束可能用作類型參數的參數的類型。
1 public class Program: BaseClass 2 { 3 new public class Test//2、new修飾符 顯式隱藏從基類繼承的成員 4 { 5 public int x = 2; 6 public int y = 20; 7 public int z = 40; 8 } 9 10 static void Main(string[] args) 11 { 12 var c1 = new Test();//1、new操作符 創建對象和調用構造函數 13 var c2 = new BaseClass.Test(); 14 Console.WriteLine(c1.x);//2 15 Console.WriteLine(c2.y);//10 16 Console.ReadKey(); 17 } 18 } 19 20 public class BaseClass 21 { 22 public class Test 23 { 24 public int x = 0; 25 public int y = 10; 26 } 27 }
new約束指定泛型類聲明中的任何類型參數都必須具有公共的無參數構造函數(http://www.cnblogs.com/kingdom_0/articles/2023499.html)
1 using System; 2 using System.Collections.Generic; 3 4 namespace ConsoleApplication2 5 { 6 public class Employee 7 { 8 private string name; 9 private int id; 10 11 public Employee() 12 { 13 name = "Temp"; 14 id = 0; 15 } 16 17 public Employee(string s, int i) 18 { 19 name = s; 20 id = i; 21 } 22 23 public string Name 24 { 25 get { return name; } 26 set { name = value; } 27 } 28 29 public int ID 30 { 31 get { return id; } 32 set { id = value; } 33 } 34 } 35 36 class ItemFactory<T> where T : new() 37 { 38 public T GetNewItem() 39 { 40 return new T(); 41 } 42 } 43 44 public class Test 45 { 46 public static void Main() 47 { 48 ItemFactory<Employee> EmployeeFactory = new ItemFactory<Employee>(); 49 ////此處編譯器會檢查Employee是否具有公有的無參構造函數。 50 //若沒有則會有The Employee must have a public parameterless constructor 錯誤。 51 Console.WriteLine("{0}'ID is {1}.", EmployeeFactory.GetNewItem().Name, EmployeeFactory.GetNewItem().ID); 52 } 53 } 54 }