How to instantiate List but T is unknown until runtime?

后端 未结 4 1199
一整个雨季
一整个雨季 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 (or rather IList<>) is not covariant in T so you cannot cast a List to a List where Foo: IFoo. You could cast it to an IEnumerable 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 is probably the best/most pragmatic way to go in this case.

    提交回复
    热议问题