简体   繁体   中英

Using Type.GetType(string) in IList<T>

Since I can't make any comments (only post an answer) to this post , I'll post a new question.
I followed the instructions from mentioned post, but the code produces an error.
The code:

Type t = Type.GetType(className);
Type listType = typeof(List<>).MakeGenericType(t);
IList list = (IList)Activator.CreateInstance(listType);

The error:

Using the generic type 'System.Collections.Generic.IList' requires '1' type arguments

Clearly I can't just state IList without any type, so I'm wondering how exactly does the answer from the mentioned post works.

Thanks in advance.

You can, you just need a different using directive:

using System.Collections;

That way you'll be using the nongeneric IList instead of the generic IList<T> .

I believe that's the spirit of the referenced answer.

Type t = Type.GetType(className);
Type listType = typeof(List<>).MakeGenericType(t);
IList list = (IList)Activator.CreateInstance(listType);

Should do the trick.

You'll have to cast the objects when retrieving them using the IList interface, but the underlying List will enforce that only objects of type T are added to the collection.

您是否尝试通过反射创建通用IList

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM