14 c# generics reflection
我有一个问题,如何可能(如果可能的话)使用Type.GetType()返回的类型引用,例如,创建该类型的IList?
这是示例代码:
Type customer = Type.GetType("myapp.Customer");
IList<customer> customerList = new List<customer>(); // got an error here =[
Run Code Online (Sandbox Code Playgroud)
先感谢您 !
Ste*_*ger 23
像这样的东西:
Type listType = typeof(List<>).MakeGenericType(customer);
IList customerList = (IList)Activator.CreateInstance(listType);
Run Code Online (Sandbox Code Playgroud)
当然你不能声明它
IList<customer>
Run Code Online (Sandbox Code Playgroud)
因为它没有在编译时定义.但List<T>实现IList,所以你可以使用它.