C#中new的三种用法

在 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 }