由Type.GetType()在C#中使用返回类型 [英] using type returned by Type.GetType() in c#
本文介绍了由Type.GetType()在C#中使用返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个关于如何可能的问题(如果可能的话:)
使用由Type.GetType()返回一个类型的参考,例如,创建该类型的IList的?
i've got a question about how is it possible (if possible :) to use a type reference returned by Type.GetType() to, for example, create IList of that type?
下面的示例code:
Type customer = Type.GetType("myapp.Customer");
IList<customer> customerList = new List<customer>(); // got an error here =[
感谢你在前进!
推荐答案
事情是这样的:
Type listType = typeof(List<>).MakeGenericType(customer);
IList customerList = (IList)Activator.CreateInstance(listType);
当然,你不能将其声明为
Of course you can't declare it as
IList<customer>
,因为它不是在编译时定义。但列表&LT; T&GT;
实现IList,所以你可以使用这个
because it is not defined at compile time. But List<T>
implements IList, so you can use this.
这篇关于由Type.GetType()在C#中使用返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文