C# 关键字:new

1、实例化对象,执行构造函数

Teacher t3 = new Teacher("张三", 100, 100, 100);

2、隐藏父类的成员

 1     class Person  2  {  3         public void SayHello()  4  {  5             Console.WriteLine("我是人类");  6  }  7  }  8 
 9     class Student : Person 10  { 11         public new void SayHello()//彻底隐藏了父类的SayHello()
12  { 13             Console.WriteLine("我是学生"); 14  } 15     }

3、约束指定泛型类声明中的任何类型参数都必须具有公共的无参构造函数

 1     class Program  2  {  3         static void Main(string[] args)  4  {  5             ItemFactory<Teacher> itemFactory = new ItemFactory<Teacher>();  6             //此处编译器会检查Teacher是否具有公有的无参构造函数。
 7             Console.WriteLine($"{itemFactory.GetNewItem().Name} ID is {itemFactory.GetNewItem().Id}");  8 
 9  Console.ReadKey(); 10  } 11  } 12     public class Teacher 13  { 14         public int Id { get; set; } 15         public string Name { get; set; } 16 
17         public Teacher() 18  { 19             Id = 1; 20             Name = "张三"; 21  } 22 
23         public Teacher(int id, string name) 24  { 25             this.Id = id; 26             this.Name = name; 27  } 28  } 29 
30     class ItemFactory<T> where T : new() 31  { 32         public T GetNewItem() 33  { 34             return new T(); 35  } 36     } 

如果没有公共的无参构造函数会报错

技术图片