public class Program: BaseClass { new public class Test//2、new修饰符 显式隐藏从基类继承的成员 { public int x = 2; public int y = 20; public int z = 40; } static void Main(string[] args) { var c1 = new Test();//1、new操作符 创建对象和调用构造函数 var c2 = new BaseClass.Test(); Console.WriteLine(c1.x);//2 Console.WriteLine(c2.y);//10 Console.ReadKey(); } } public class BaseClass { public class Test { public int x = 0; public int y = 10; } }
new约束指定泛型类声明中的任何类型参数都必须具有公共的无参数构造函数
using System; using System.Collections.Generic; namespace ConsoleApplication2 { public class Employee { private string name; private int id; public Employee() { name = "Temp"; id = 0; } public Employee(string s, int i) { name = s; id = i; } public string Name { get { return name; } set { name = value; } } public int ID { get { return id; } set { id = value; } } } class ItemFactory<T> where T : new() { public T GetNewItem() { return new T(); } } public class Test { public static void Main() { ItemFactory<Employee> EmployeeFactory = new ItemFactory<Employee>(); ////此处编译器会检查Employee是否具有公有的无参构造函数。 //若没有则会有The Employee must have a public parameterless constructor 错误。 Console.WriteLine("{0}'ID is {1}.", EmployeeFactory.GetNewItem().Name, EmployeeFactory.GetNewItem().ID); } } }
作者: 码农谷城
出处:https://www.cnblogs.com/codedisco/p/12568489.html
版权:本文采用「署名-非商业性使用-相同方式共享 4.0 国际」知识共享许可协议进行许可。