简体   繁体   English

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

[英]C# - How to pass generic type with type of “this” class

I have a User class that has a GetQueryable method.我有一个具有GetQueryable方法的User类。 Another method, Select() , calls GetQueryable() .另一种方法Select()调用GetQueryable() I want to use the Select method without passing the type User to the Select method, because I have it in this but I can't use it.我想使用的Select方法,而没有经过类型UserSelect的方法,因为我有这个,但我不能使用它。

Type type = this.GetType(); Type type = this.GetType();

??? ???

var x = this.GetQueryable< ??? 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;
    }
}

You can do it using reflection.您可以使用反射来做到这一点。 The following sample works smoothly.以下示例运行顺利。 In program you can use Clerk or Manager , just any instance derived from User to call Select .在程序中,您可以使用ClerkManager ,只是从User派生的任何实例来调用Select You can improve your program with this.你可以用这个来改进你的程序。

    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();
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM