开发者

Create list of variable type

I a开发者_运维问答m 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 create a list of a variable type?

I want something similar to this code.

public IList createListOfMyType(Type myType)
{
     return new List<myType>();
}


Something like this should work.

public IList createList(Type myType)
{
    Type genericListType = typeof(List<>).MakeGenericType(myType);
    return (IList)Activator.CreateInstance(genericListType);
}


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[] {});


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜