一下代码没写完,写不下去了,不能执行。我想做的就是在IMSDB()构造函数中反射获取所有的成员。并实例化后把实例对象赋给他们。实现Memos,Persons,Users以及更多成员的批量实例化。
public class IMSDB : DBController { public DbSet<Memo> Memos { get; set; } public DBSet<Person> Persons { get; set; } public List<User> Users { get; set; } public IMSDB() { //Persons = new DBSet<Person>(); var type = this.GetType(); //反射解析 获取成员列表 System.Reflection.PropertyInfo[] properties = type.GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public); if (properties.Length > 0) { foreach (System.Reflection.PropertyInfo item in properties) { Type t = item.PropertyType.GetGenericArguments()[0]; //泛型中实体的类型 object o = t.GetConstructor(new Type[0]).Invoke(new object[0]); //实例化实体类 item.SetValue(t, o, null); } } }
1 回答
月关宝盒
你那个SetValue时的第一个参数应该是this,而不是t,没有完整代码,只能揣测了。
TA贡献1772条经验 获得超5个赞
foreach(var pi in properties)
{
var instance = Activator.CreateInstance(pi.PropertyType);
pi.SetValue(this,instance,null);
}
- 1 回答
- 0 关注
- 366 浏览
添加回答
举报
0/150
提交
取消