我有一个具有GetQueryable
方法的User
类。另一个方法Select()
调用GetQueryable()
。我想使用Select
方法而不将类型User
传递给Select
方法,因为我在这个中有它,但我不能使用它。
Type type =
this.GetType();
? ?
var x = this.GetQueryable<
??>().ToList();
class Program
{
static void Main(string[] args)
{
var acc = new User();
acc.Select();
}
}
public partial class User
{
public DB_Test001Entities context;
public User()
{
context = new DB_Test001Entities();
}
public void Select()
{
Type type = this.GetType();
var x = this.GetQueryable< **???** >().ToList();
}
public IQueryable<TEntity> GetQueryable<TEntity>(List<string> includes = null) where TEntity : class
{
IQueryable<TEntity> items = context.Set<TEntity>();
if (includes != null && includes.Any())
includes.Where(i => i != null).ToList().ForEach(i => { items = items.Include(i); });
return items;
}
}
您可以使用反射来实现。下面的示例工作得很顺利。在程序中,您可以使用Clerk
或Manager
,只是从User
派生的任何实例调用Select
。你可以用这个改进你的程序。
class Clerk : User { }
class Manager : User { }
internal class User
{
public User() { }
public string Name { get; set; }
public void Select()
{
var list = new List<string>() {"Jack", "Martin"};
Type thisType = GetType();
MethodInfo method = thisType.GetMethod("GetQueryable").MakeGenericMethod(thisType);
method.Invoke(this, new object[] {list});
}
public IQueryable<TEntity> GetQueryable<TEntity>(List<string> includes = null) where TEntity : User, new()
{
if(includes != null)
{
Console.WriteLine(typeof(TEntity));
var entity = new List<TEntity>(includes.Count);
entity.AddRange(includes.Select(item => new TEntity {Name = item}));
return entity.AsQueryable();
}
return null;
}
}
class Program
{
static void Main()
{
User usr = new Manager();
usr.Select();
}
}