How to instantiate List but T is unknown until runtime?

后端 未结 4 1182
一整个雨季
一整个雨季 2020-12-31 10:05

Assume I have a class that is unknown until runtime. At runtime I get a reference, x, of type Type referencing to Foo.GetType(). Only by using x and List<>, can I create

相关标签:
4条回答
  • 2020-12-31 10:43

    Sure you can:

    var fooList = Activator
        .CreateInstance(typeof(List<>)
        .MakeGenericType(Foo.GetType()));
    

    The Problem here is that fooList is of type object so you still would have to cast it to a "usable" type. But what would this type look like? As a data structure supporting adding and looking up objects of type T List<T> (or rather IList<>) is not covariant in T so you cannot cast a List<Foo> to a List<IFoo> where Foo: IFoo. You could cast it to an IEnumerable<T> which is covariant in T.

    If you are using C# 4.0 you could also consider casting fooList to dynamic so you can at least use it as a list (e.g. add, look-up and remove objects).

    Considering all this and the fact, that you don't have any compile-time type safety when creating types at runtime anyhow, simply using a List<object> is probably the best/most pragmatic way to go in this case.

    0 讨论(0)
  • 2020-12-31 10:47
    Type x = typeof(Foo);
    Type listType = typeof(List<>).MakeGenericType(x);
    object list = Activator.CreateInstance(listType);
    

    Of course you shouldn't expect any type safety here as the resulting list is of type object at compile time. Using List<object> would be more practical but still limited type safety because the type of Foo is known only at runtime.

    0 讨论(0)
  • 2020-12-31 10:51

    Given a type, you can instantiate a new instance this way:

    var obj = Activator.CreateInstance(type);
    

    Ref: http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx

    0 讨论(0)
  • 2020-12-31 11:01

    Something like this:

    Activator.CreateInstance(typeof(List<>).MakeGenericType(type))

    0 讨论(0)
提交回复
热议问题