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.
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.