为了账号安全,请及时绑定邮箱和手机立即绑定

帮忙写一段实例化的反射,谢谢

帮忙写一段实例化的反射,谢谢

吃鸡游戏 2018-12-07 07:08:22
一下代码没写完,写不下去了,不能执行。我想做的就是在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 回答

?
月关宝盒

TA贡献1772条经验 获得超5个赞

foreach(var pi in properties)
{
var instance
= Activator.CreateInstance(pi.PropertyType);
pi.SetValue(
this,instance,null);
}
你那个SetValue时的第一个参数应该是this,而不是t,没有完整代码,只能揣测了。
查看完整回答
反对 回复 2019-01-21
  • 1 回答
  • 0 关注
  • 366 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信