【问题标题】:Why am I getting a compile error when I'm trying to create a list of a dynamic object at runtime?当我尝试在运行时创建动态对象列表时,为什么会出现编译错误?
【发布时间】:2009-09-03 16:30:11
【问题描述】:

我做了一些研究,发现显然有一种使用反射的简单易懂的方法来做到这一点。

Type MyType = typeof(MyObject);
IList lst = (IList)Activator.CreateInstance((typeof(List<>).MakeGenericType(MyType)));  

我收到编译错误。它告诉我实际上确实需要将类型提供给 IList ...... 我错过了什么吗?

任何帮助将不胜感激,干杯。

【问题讨论】:

  • 如果只能通过非泛型IList接口访问,为什么还要创建List&lt;T&gt;的动态实例?
  • 因为我需要该列表来调用某个对象的构造函数,而我只会在运行时知道...

标签: c# .net reflection list


【解决方案1】:

你忘了这个:

using System.Collections;

没有它,它只会看到System.Collections.Generic.IList&lt;T&gt;,因此会抱怨缺少T

【讨论】:

    猜你喜欢
    • 2013-08-14
    • 1970-01-01
    • 2021-12-21
    • 2021-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多