在.Net中,微软给我们提供了很多不同的创建对象实例的方法,它们的速度又各有不同,以下一一列举。 使用new关键字 这在.Net中是最常见,也是速度最快的方式: 1 var instance = new Class(); 使用System.Activator类的CreateInstance方法动态创建 这里的CreateInstance指的是Activator的非泛型方法: 1 var instance = System.Activator.CreateInstance(typeof(Class)); 使用System.Activator类的CreateInstance方法动态创建 这里的CreateInstance才是Activator的泛型方法: 1 var instance = System.Activator.CreateInstance(); 使用泛型约束,使用new关键字创建对象(泛型方法) 首先需要创建一个泛型的方法: 1 public static T CreateInstance() where T : new() 2 { 3 return new T(); 4 } 这里利用泛型约束where T: new(),保证了T类型是可以用无参构造器构造的,所以代码里面就可以直接使用new T()来创建对象: 1 var instance = CreateInstance(); 使用泛型类的静态方法、泛型约束和new关键字创建 这里需要首先创建一个泛型类 1 public static class StaticInitializer where T:new() 2 { 3 public static T CreateInstance() 4 { 5 return new T(); 6 } 7 } 然后使用如下代码创建实例: 1 var instance = StaticInitializer.CreateInstance(); 使用泛型类的动态方法、泛型约束和new关键字 这里使用的是泛型类的实力方法,需要首先创建一个泛型类: 1 public class DynamicInitializer where T:new() 2 { 3 public T CreateInstance() 4 { 5 return new T(); 6 } 7 } 使用的方法就是: 1 var initializer = new DynamicInitializer(); 2 var instance = initializer.CreateInstance(); Ok,现在我一共提出了6种不同的创建对象的方式,大家可以猜猜这些创建对象的方式当中那个会比较快。 使用new关键字 使用System.Activator类的CreateInstance方法动态创建 使用System.Activator类的CreateInstance方法动态创建 使用泛型约束,使用new关键字创建对象(泛型方法) 使用泛型类的静态方法、泛型约束和new关键字创建 使用泛型类的动态方法、泛型约束和new关键字
|