反射创建对象,创建泛型集合,创建泛型字典
2010-12-22 17:13 Virus-BeautyCode 阅读(2871) 评论(1) 编辑 收藏 举报
object obj = new object();
//反射创建普通对象
object o = Activator.CreateInstance(obj.GetType());
//反射创建泛型集合
Type generic = typeof(List<>);
Type[] typeArgs1 = { obj.GetType() };
generic=generic.MakeGenericType(typeArgs1);
var list=Activator.CreateInstance (generic) as IList;
//反射创建泛型字典
generic = typeof(Dictionary<,>);
Type[] typeArgs2 = { typeof(string), obj.GetType() };
generic = generic.MakeGenericType(typeArgs2);
var dic = Activator.CreateInstance(generic) as IDictionary;
//反射创建普通对象
object o = Activator.CreateInstance(obj.GetType());
//反射创建泛型集合
Type generic = typeof(List<>);
Type[] typeArgs1 = { obj.GetType() };
generic=generic.MakeGenericType(typeArgs1);
var list=Activator.CreateInstance (generic) as IList;
//反射创建泛型字典
generic = typeof(Dictionary<,>);
Type[] typeArgs2 = { typeof(string), obj.GetType() };
generic = generic.MakeGenericType(typeArgs2);
var dic = Activator.CreateInstance(generic) as IDictionary;