2

由于我无法对此帖子发表任何评论(仅发布答案),因此将发布一个新问题。
我按照上述帖子中的说明进行操作,但代码会产生错误。
编码:

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

错误:

使用泛型类型“System.Collections.Generic.IList”需要“1”类型参数

显然,我不能只说IList没有任何类型,所以我想知道上述帖子的答案究竟是如何工作的。

提前致谢。

4

3 回答 3

9

你可以,你只需要一个不同的 using 指令:

using System.Collections;

这样,您将使用非IList泛型而不是泛型IList<T>

我相信这就是参考答案的精神。

于 2010-06-25T15:01:13.620 回答
1
Type t = Type.GetType(className);
Type listType = typeof(List<>).MakeGenericType(t);
IList list = (IList)Activator.CreateInstance(listType);

应该做的伎俩。

在使用 IList 接口检索对象时,您必须强制转换对象,但底层 List 将强制仅将 T 类型的对象添加到集合中。

于 2010-06-25T15:04:14.517 回答
0

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

于 2010-06-25T15:01:42.077 回答