第一个问题:
Activator.CreateInstance(tempListProperty.PropertyType);
不要用GetType.Assembly那种方式闯将。具体为什么我不知道,只是用前者可以成功,后者就是null
期待牛牛给出解释第二个问题:
Invoke(tempStu, new Object[] { tempTest });
第一个参数不对,应该是Property所属的对象,在该问题中,第一个参数应为tempList
Activator.CreateInstance(tempListProperty.PropertyType);
不要用GetType.Assembly那种方式闯将。具体为什么我不知道,只是用前者可以成功,后者就是null
期待牛牛给出解释第二个问题:
Invoke(tempStu, new Object[] { tempTest });
第一个参数不对,应该是Property所属的对象,在该问题中,第一个参数应为tempList
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();
但就你的这个代码来说,Main方法都依赖于Student类了,还要去反射才知道List<ParentInfo>类型吗?这在正规的代码里,就成了多余的代码了。即使是扩展性好的设计中,也要使用接口、依赖接口来扩展。不要盲目滥用反射。
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);