Create list of variable type

前端 未结 3 651
谎友^
谎友^ 2020-11-28 11:14

I am trying to create a list of a certain type.

I want to use the List notation but all I know is a \"System.Type\"

The type a have is variable. How can I cr

相关标签:
3条回答
  • 2020-11-28 11:23

    Something like this should work.

    public IList createList(Type myType)
    {
        Type genericListType = typeof(List<>).MakeGenericType(myType);
        return (IList)Activator.CreateInstance(genericListType);
    }
    
    0 讨论(0)
  • 2020-11-28 11:32

    You could use Reflections, here is a sample:

        Type mytype = typeof (int);
    
        Type listGenericType = typeof (List<>);
    
        Type list = listGenericType.MakeGenericType(mytype);
    
        ConstructorInfo ci = list.GetConstructor(new Type[] {});
    
        List<int> listInt = (List<int>)ci.Invoke(new object[] {});
    
    0 讨论(0)
  • 2020-11-28 11:45

    Thank you! This was a great help. Here's my implementation for Entity Framework:

        public System.Collections.IList TableData(string tableName, ref IList<string> errors)
        {
            System.Collections.IList results = null;
    
            using (CRMEntities db = new CRMEntities())
            {
                Type T = db.GetType().GetProperties().Where(w => w.PropertyType.IsGenericType && w.PropertyType.GetGenericTypeDefinition() == typeof(System.Data.Entity.DbSet<>)).Select(s => s.PropertyType.GetGenericArguments()[0]).FirstOrDefault(f => f.Name == tableName);
                try
                {
                    results = Utils.CreateList(T);
                    if (T != null)
                    {
                        IQueryable qrySet = db.Set(T).AsQueryable();
                        foreach (var entry in qrySet)
                        {
                            results.Add(entry);
                        }
                    }
                }
                catch (Exception ex)
                {
                    errors = Utils.ReadException(ex);
                }
            }
    
            return results;
        }
    
        public static System.Collections.IList CreateList(Type myType)
        {
            Type genericListType = typeof(List<>).MakeGenericType(myType);
            return (System.Collections.IList)Activator.CreateInstance(genericListType);
        }
    
    0 讨论(0)
提交回复
热议问题