第一个问题:
Activator.CreateInstance(tempListProperty.PropertyType);
不要用GetType.Assembly那种方式闯将。具体为什么我不知道,只是用前者可以成功,后者就是null
期待牛牛给出解释第二个问题:
Invoke(tempStu, new Object[] { tempTest });
第一个参数不对,应该是Property所属的对象,在该问题中,第一个参数应为tempList

解决方案 »

  1.   

    var list = typeof(List<>).MakeGenericType(typeof(ParentInfo));
      

  2.   

    本帖最后由 caozhy 于 2011-07-06 18:22:48 编辑
      

  3.   

    给你找一篇很老的帖子:http://www.cnblogs.com/ninputer/articles/415458.html
      

  4.   

    贴个完整点的:var listType = typeof(List<>).MakeGenericType(typeof(ParentInfo));
    var list = Activator.CreateInstance(listType);
    var addMethod = listType.GetMethod("Add");
    var parent = new ParentInfo { Name = "test", Birthday = "1980/1/1" };
    addMethod.Invoke((object)list, new object[] { parent });
    var count = listType.GetProperty("Count").GetValue(list, null);
    Console.WriteLine(count);
    Console.Read();
      

  5.   


    但就你的这个代码来说,Main方法都依赖于Student类了,还要去反射才知道List<ParentInfo>类型吗?这在正规的代码里,就成了多余的代码了。即使是扩展性好的设计中,也要使用接口、依赖接口来扩展。不要盲目滥用反射。
      

  6.   

    下面这一句是错的
    var tempList = tempStu.GetType().Assembly.CreateInstance(tempListProperty.PropertyType.FullName);注意下。tempStu.GetType().Assembly是获得了 tempStu所在的程序集,该程序集是你创建代码的 控制台 的那个项目生成的程序集。而List<T> 不在这个程序集内,他位于 System.Collections.Generic命名空间下,位于 mscorlib.dll 程序集内。所以这里的反射CreateInstance是无法找到这个类的,当然始终会返回null.
               
    注意某个类在哪个程序集内被声明。
    List<ParentInfo> tempList = null; //tempStu.GetType().Assembly.CreateInstance(tempListProperty.PropertyType);
    object obj =  Activator.CreateInstance(tempListProperty.PropertyType);