开发者

Dynamic List<T> type [duplicate]

This question already has answers here: Pass An Instantiated System.Type as a Type Parameter for a Generic Class (6 answers) 开发者_如何转开发 Closed 8 years ago.

Is it possible to create a new List<T> where the T is dynamically set at runtime?

Cheers


It's possible, but not necessarily useful, since you couldn't actually use it from compiled code as strongly typed. The creation code would be

    Type myType;
    Type listType = typeof(List<>).MakeGenericType(myType);
    IList myList = (IList)Activator.CreateInstance(listType);


Yes. You can do this via Reflection, using Type.MakeGenericType and Activator.CreateInstance.

IList MakeListOfType(Type listType)
{
    Type listType = typeof(List<>);
    Type specificListType = listType.MakeGenericType(listType);

    return (IList)Activator.CreateInstance(specificListType);
}


Yes. However, you won't be able to assign it to a variable that has a generic type since the T in this case will not be decided until runtime. (If you are thinking that the .NET 4.0 covariance feature will help you and let you declare the variable as IList<SomeSuperType>, it won't as the T is used by List<T> for both in and out purposes.)

Note the unusual List<> syntax in order to access the "unconstructed" generic type.

    public static System.Collections.IList ConstructGenericList(Type t)
    {
        return (System.Collections.IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(t));
    }


For DataContractSerializer Known Types you may want to supply not only types from your assembly but also list of that types:

public static List<Type> GetKnownTypesForDataContractSerializer()
{
    Assembly a = Assembly.GetExecutingAssembly();
    Type[] array = a.GetExportedTypes();

    List<Type> lista = array.ToList();

    lista = lista.FindAll(item => ((item.IsClass || item.IsEnum) & !item.IsGenericType & !item.IsAbstract == true));



    List<Type> withEnumerable = new List<Type>();
    foreach (Type t in lista)
    {
        withEnumerable.Add(t);   //add basic type

        //now create List<> type
        Type listType = typeof(List<>);
        var listOfType = listType.MakeGenericType(t);

        withEnumerable.Add(listOfType);  //add Type of List<basic type>  
    }

    return withEnumerable;
}


yes using generic you can do something like this

    var asd = METHOD<Button>();

    List<t> METHOD<t>()
    {
        return new List<t>();
    }
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜