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

一下代码没写完,写不下去了,不能执行。我想做的就是在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);
}
}
}

吃鸡游戏
浏览 367回答 1
1回答

月关宝盒

foreach(var pi in properties){ var instance = Activator.CreateInstance(pi.PropertyType); pi.SetValue(this,instance,null);} 你那个SetValue时的第一个参数应该是this,而不是t,没有完整代码,只能揣测了。
打开App,查看更多内容
随时随地看视频慕课网APP