日期:2014-05-16 浏览次数:21031 次
/// <summary>
/// 语言:C#
/// 版本:4.0
/// 环境:vs2010
/// </summary>
public class Program
{
static void Main(string[] args)
{
Student tempStu = new Student();
//获取属性ParentInfoList
var tempListProperty = tempStu.GetType().GetProperty("ParentInfoList");
//通过属性的类型,动态创建对象
//
//问题1:这里的值永远为null
var tempList = tempStu.GetType().Assembly.CreateInstance(tempListProperty.PropertyType.FullName);
tempListProperty.SetValue(tempStu, tempList, null);
var tempTest = typeof(ParentInfo).Assembly.CreateInstance("ConsoleApplication20.Test");
//问题2:这里会提示类型不匹配
tempListProperty.PropertyType.GetMethod("Add").Invoke(tempStu, new Object[] { tempTest });
}
}
public class Student
{
public List<ParentInfo> ParentInfoList { get; set; }
public String ID { get; set; }
}
public class ParentInfo
{
public String Name { get; set; }
public String Birthday { get; set; }
}
var listType = typeof(List<>).MakeGenericType(typeof(ParentInfo));
var list = Activator.CreateInstance(listType);
var addMethod&n