Activator包含特定的方法,用以在本地或从远程创建对象类型,或获取对现有远程对象的引用。此类不能被继承。
具体介绍:http://msdn.microsoft.com/zh-cn/library/vstudio/system.activator.aspx
下面我举一个用Activator 创建同样类型的实例:
在这里要注意的是。范型中不能用Activator创建包含范型变量的实例。见下面结果
class DictionaryString<T>:Dictionary<string ,T>{} public class Generic2 { public void mianFunction() { object o = null; Type t=typeof(Dictionary<,>); o = CreateInstance(t); Type t2=typeof(DictionaryString<string>); o = CreateInstance(t2); } private object CreateInstance(Type t) { object o = null; try { o = Activator.CreateInstance(t); Console.WriteLine("已经创建该类型的实例:"+t.ToString()); } catch (Exception e){ Console.WriteLine(e.Message); } return o; } }
结果:
无法创建 System.Collections.Generic.Dictionary`2[TKey,TValue] 的实例,因为 Type.
ContainsGenericParameters 为 True。
已经创建该类型的实例:Generic.DictionaryString`1[System.String]