一次面試中面試員問在C#中關於new關鍵字使用的三種方法,當時只回答了一種,面試結束後查詢了一下有三種方法(參照MSDN)。下面把這三種方法介紹下:面試
經過使用 new 運算符建立並初始化一個 struct 對象和一個類對象,而後爲它們賦值。 顯示了默認值和所賦的值。ide
1 struct SampleStruct 2 { 3 public int x; 4 public int y; 5 6 public SampleStruct(int x, int y) 7 { 8 this.x = x; 9 this.y = y; 10 } 11 } 12 13 class SampleClass 14 { 15 public string name; 16 public int id; 17 18 public SampleClass() {} 19 20 public SampleClass(int id, string name) 21 { 22 this.id = id; 23 this.name = name; 24 } 25 } 26 27 class ProgramClass 28 { 29 static void Main() 30 { 31 // Create objects using default constructors: 32 SampleStruct Location1 = new SampleStruct(); 33 SampleClass Employee1 = new SampleClass(); 34 35 // Display values: 36 Console.WriteLine("Default values:"); 37 Console.WriteLine(" Struct members: {0}, {1}", 38 Location1.x, Location1.y); 39 Console.WriteLine(" Class members: {0}, {1}", 40 Employee1.name, Employee1.id); 41 42 // Create objects using parameterized constructors: 43 SampleStruct Location2 = new SampleStruct(10, 20); 44 SampleClass Employee2 = new SampleClass(1234, "Cristina Potra"); 45 46 // Display values: 47 Console.WriteLine("Assigned values:"); 48 Console.WriteLine(" Struct members: {0}, {1}", 49 Location2.x, Location2.y); 50 Console.WriteLine(" Class members: {0}, {1}", 51 Employee2.name, Employee2.id); 52 } 53 } 54 /* 55 Output: 56 Default values: 57 Struct members: 0, 0 58 Class members: , 0 59 Assigned values: 60 Struct members: 10, 20 61 Class members: Cristina Potra, 1234 62 */
基類 BaseC 和派生類 DerivedC 使用相同的字段名 x,從而隱藏了繼承字段的值。 此示例演示 new 修飾符的用法。 另外還演示瞭如何使用徹底限定名訪問基類的隱藏成員。函數
1 public class BaseC 2 { 3 public static int x = 55; 4 public static int y = 22; 5 } 6 7 public class DerivedC : BaseC 8 { 9 // Hide field 'x'. 10 new public static int x = 100; 11 12 static void Main() 13 { 14 // Display the new value of x: 15 Console.WriteLine(x); 16 17 // Display the hidden value of x: 18 Console.WriteLine(BaseC.x); 19 20 // Display the unhidden member y: 21 Console.WriteLine(y); 22 } 23 } 24 /* 25 Output: 26 100 27 55 28 22 29 */
當泛型類建立類型的新實例,請將 new 約束應用於類型參數,以下面的示例所示:ui
1 class ItemFactory<T> where T : new() 2 { 3 public T GetNewItem() 4 { 5 return new T(); 6 } 7 } 8 9 當與其餘約束一塊兒使用時,new() 約束必須最後指定: 10 public class ItemFactory2<T> 11 where T : IComparable, new() 12 { 13 }