How to instantiate List but T is unknown until

2020-02-26 08:51发布

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 a list of type Foo?

How to do that?

标签: c#
4条回答
小情绪 Triste *
2楼-- · 2020-02-26 09:31

Something like this:

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

查看更多
做个烂人
3楼-- · 2020-02-26 09:34

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.

查看更多
家丑人穷心不美
4楼-- · 2020-02-26 09:41

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

查看更多
叛逆
5楼-- · 2020-02-26 09: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.

查看更多
登录 后发表回答