我想将字符串更改为使用swich case语句的entityType交换来查找Type
类似的东西:
private void methodName(string entityTypeName)
{
Type myEFType = Type.GetType(entityTypeName);
//object d = Activator.CreateInstance(type); //this create instance from my entityType very Well
var myEFTypeCollection = _db.Set<(here need cast) myEFType>();
}
我认为必须使用 Convert.ChangeType(),但是如何?
答案 0 :(得分:0)
您可以使用MakeGeneric()方法
System.Reflection.MethodInfo mi = typeof(API).GetMethod("DoSomething", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
mi.MakeGenericMethod(typeof(Type.GetType(entityTypeName))).Invoke(new API(),new object[]{_db});
class API
{
private void DoSomething<T>(DbContext db)
{
IQueryable<T> items = db.Set<T>();
// Do something you need .....
}
}