请举一个简单易懂的小例子来说明…
反射普通类和反射泛型类是不同的…
public abstract class BusinessManager
{
/// <summary>
/// 添加一个新实体
/// </summary>
/// <param name="entity"></param>
public virtual void Add<T>(T MappedInstance) where T : Entity
{
Type entitymanage = typeof(EntityManager<T>);
object obj = Activator.CreateInstance(entitymanage);
MethodInfo method = entitymanage.GetMethod("Add");
method.Invoke(obj, new object[] { MappedInstance });
}
}
类似这样的,但是这是使用反射普通类的方法,在这里有错误,希望帮我改成可以反射泛型类的,将这个改一下。
EntityManager<T>是一个泛型类
new方法无法创建实例
反射普通类和反射泛型类是不同的…
public abstract class BusinessManager
{
/// <summary>
/// 添加一个新实体
/// </summary>
/// <param name="entity"></param>
public virtual void Add<T>(T MappedInstance) where T : Entity
{
Type entitymanage = typeof(EntityManager<T>);
object obj = Activator.CreateInstance(entitymanage);
MethodInfo method = entitymanage.GetMethod("Add");
method.Invoke(obj, new object[] { MappedInstance });
}
}
类似这样的,但是这是使用反射普通类的方法,在这里有错误,希望帮我改成可以反射泛型类的,将这个改一下。
EntityManager<T>是一个泛型类
new方法无法创建实例
请大家帮忙看一下~
http://blog.csdn.net/ojlovecd/archive/2008/09/17/2943968.aspx
}
public virtual void Add <T>(T MappedInstance) where T :Entity
Type t = typeof(List<string>);
List<string> lst = (List<string>)Activator.CreateInstance(t); lst.Add("aaa");
lst.Add("bbb"); MessageBox.Show(lst[0]);
Type t = typeof(List<string>);
Object obj = Activator.CreateInstance(t); MethodInfo method = t.GetMethod("Add"); string[] str = new string[1] { "1111"};
method.Invoke(obj, str); MessageBox.Show(((List<string>)obj)[0]);
public virtual void Add<T>(T MappedInstance) where T : Entity
{
Type entityManagerType = typeof(EntiryManager<>);
Type generiManagerType = entityManagerType.MakeGenericType(typeof(T)); //<-------
object obj = Activator.CreateInstance(generiManagerType); MethodInfo method = generiManagerType.GetMethod("Add");
method.Invoke(obj, new object[] { MappedInstance });
}