C# - 如何传递类型为“this”类的泛型类型

时间:2014-06-26 04:09:28

标签: c# entity-framework generics dynamic reflection

我有一个User类,它有一个GetQueryable方法。另一个名为Select()的方法调用GetQueryable()。我想使用Select方法而不在Select方法中传递用户类的类型,因为我在这个中有它但我无法使用它。帮我 输入t

  

输入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;
    }
}

1 个答案:

答案 0 :(得分:3)

你可以使用Reflection做到这一点。以下示例工作顺利。在程序中,您可以使用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();
        }
}
相关问题